4

I've been trying to pass a multidimensional array, of an unknown size, to a function, and so far have had no luck, when the array is declared, its dimensions are variables:

double a[b][b];

As far as I can tell, I need to give the value of b when I declare the function, a can be unknown. I tried declaring b as a global variable, but it then says that it must be a constant.

ie:

int b;

double myfunction(array[][b])
{
}

int main()
{
int a;
double c;
double myarray[a][b];

c=myfunction(myarray);

return 0;
}

Is there any way get this to work?

7
  • 1
    Not very pretty, but can you not just pass in the pointer to the first element? Commented Jul 25, 2012 at 17:33
  • 2
    std::vector makes life so much easier. Commented Jul 25, 2012 at 17:34
  • 3
    If the dimensions are variable use either std::vector or boost::multiarray. Commented Jul 25, 2012 at 17:34
  • I know this doesn't answer your question, but you are missing double in front of your array parameter. I don't know if this is an oversight in your post here or if it is missing from the code you are compiling as well. Commented Jul 25, 2012 at 17:46
  • @chris, std::vector makes life easier for single-dimension arrays but it complicates multi-dimension arrays since the size of each row must be set separately. Commented Jul 25, 2012 at 18:04

4 Answers 4

4

Pass by value :

double myfunction(double (*array)[b]) // you still need to tell b

Pass by ref :

double myfunction(int (&myarray)[a][b]); // you still need to tell a and b

Template way :

template<int a, int b> double myfunction(int (&myarray)[a][b]); // auto deduction
Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps reading some references on C++ and arrays would help,

http://en.cppreference.com/w/cpp/container/array

Comments

1

if you want to pass an array of unknown size you can declare an array in Heap like this

//Create your pointer
int **p;
//Assign first dimension
p = new int*[N];
//Assign second dimension
for(int i = 0; i < N; i++)
p[i] = new int[M];


 than you can declare a function like that: 
double myFunc (**array);

Comments

-1
void procedure (int myarray[][3][4])

More on this here

2 Comments

I think this is a 3-dimensional array instead of 2, or else you've found a syntax that I've never seen before [which is admittedly possible! :)]
See Griwes's comment on the other answer. A better link would be this question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.