user1035957
user1035957

Reputation: 327

Compiler error when passing 2D array to a function without specifiying 2nd dimension

Why does this work:

void SomeFunction(int SomeArray[][30]);

but this doesn't?

void SomeFunction(int SomeArray[30][]);

Upvotes: 2

Views: 191

Answers (2)

Intuitively, because the compiler cannot compute a constant size for the elements of the formal in the second declaration. Each element there has type int[] which has no known size at compile time.

Formally, because the standard C++ specification disallow that syntax!

You might want to use std::array or std::vector templates of C++11.

Upvotes: 2

iammilind
iammilind

Reputation: 69988

Because, when passing an array as an argument the first [] is optional, however the 2nd onwards parameters are mandatory. That is the convention of the language grammar.

Moreover, you are not actually passing the array, but a pointer to the array of elements [30]. For better explanation, look at following:

T a1[10], a2[10][20];
T *p1;    // pointer to an 'int'
T (*p2)[20];  // pointer to an 'int[20]'

p1 = a1;  // a1 decays to int[], so can be pointed by p1
p2 = a2;  // a2 decays to int[][20], so can be pointed by p2

Also remember that, int[] is another form of int* and int[][20] is another form of int (*)[20]

Upvotes: 2

Related Questions