[C++] Passing a multi-dim. array to function - Error.

This topic is 4203 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hey! I'm learning C++ and I'm experiencing something a bit strange, to me at least. My compiler allows this:
int main() {
int i = 5;
int j = 5;
int arr[j];
}

And this:
void arrayFunction(int a[][5]) {
}

int main() {
int arr[5][5];
arrayFunction(arr);
}

But not this:
void arrayFunction(int a[][5]) {
}

int main() {
int i = 5;
int j = 5;
int arr[j];
arrayFunction(arr);  //line L
}

Giving this message about line L: cannot convert int (*)[((unsigned int)((int)j))]' to int (*)[5]' for argument 1' to void arrayFunction(int (*)[5])' I noticed one compiler (online at a code pasting site) that did not allow the first piece of code, so maybe that's something one should not do. And in that case, how am I supposed to know what array size I'm going to need when I write the code.

Share on other sites
The first example is non-standard, since C++ does not allow dynamic-sized stack arrays. The dimentsions must be compile-time constants.

If you want to define dimensions at runtime, use the appropriate tools, such as boost::multi_array, or encapsulate your array in a class that handles the allocation and can also be passed as an argument.

Share on other sites

But, can I do that with arrays on the heap?

Share on other sites
Heap arrays can only have one dimension, although you may be able to emulate multi-dimensional arrays using pointer-to-pointer tricks. Either way, these best belong inside a nice, tight-wrapped class.

Share on other sites
The problem is, that you try to make a dynamically sized array by passing in two variables as a size.

try either writing
const int i = 5;const int j = 5;int arr[j];

or allocate the array dynamically
int i = 5;int j = 5;int arr[][] = new int*;for( int n = 0; n < i; ++n ) arr[n] = new int[j];// some code herefor( int n = 0; n < i; ++n ) delete[] arr[n];delete[] arr;

t0}{!c

Share on other sites
So the one-dimensional array on the heap can have their size decided in runtime?

Share on other sites
Quote:
 Original post by tufflaxSo the one-dimensional array on the heap can have their size decided in runtime?

Yes, that is the point of operator new[].

Share on other sites
I've not gotten that far in my book yet, but thanks!