Sign in to follow this  
tufflax

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

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[i][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[i][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 this post


Link to post
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 this post


Link to post
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 this post


Link to post
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[i][j];


or allocate the array dynamically


int i = 5;
int j = 5;
int arr[][] = new int*[i];
for( int n = 0; n < i; ++n ) arr[n] = new int[j];

// some code here

for( int n = 0; n < i; ++n ) delete[] arr[n];
delete[] arr;


t0}{!c

Share this post


Link to post
Share on other sites
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[].

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this