简体   繁体   English

未指定第二维时将2D数组传递给函数时的编译器错误

[英]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. 那里的每个元素都具有int[]类型,该类型在编译时不知道大小。

Formally, because the standard C++ specification disallow that syntax! 正式地,因为标准的C ++规范不允许该语法!

You might want to use std::array or std::vector templates of C++11. 您可能要使用C ++ 11的std::arraystd::vector模板。

Because, when passing an array as an argument the first [] is optional, however the 2nd onwards parameters are mandatory. 因为在将数组作为参数传递时,第一个[]是可选的,但是第2个之后的参数是必需的。 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] . 而且,您实际上不是在传递数组,而是指向元素数组的指针[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] 还请记住, int[]int*另一种形式,而int[][20]int (*)[20]另一种形式

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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