• Advertisement
Sign in to follow this  

[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.

If you intended to correct an error in the post then please contact us.

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


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

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[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 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
So the one-dimensional array on the heap can have their size decided in runtime?

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
Sign in to follow this  

  • Advertisement