简体   繁体   中英

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][]);

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM