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

Started by
6 comments, last by tufflax 17 years, 8 months ago
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.
Advertisement
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.
Thanks for your answer!

But, can I do that with arrays on the heap?
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.
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
So the one-dimensional array on the heap can have their size decided in runtime?
Quote:Original post by tufflax
So the one-dimensional array on the heap can have their size decided in runtime?


Yes, that is the point of operator new[].
I've not gotten that far in my book yet, but thanks!

This topic is closed to new replies.

Advertisement