当一个多维数组被传递给函数时,为什么C++要求在参数列表中指定除第一维之外的所有维度?
void f(int *p);
void f(int p[]);
void f(int p[10]);
void f(int p[100]);
在该函数中,当导航指向p
的数组时,编译器所需的唯一信息是数组元素的大小,例如在这种情况下是sizeof(int)
。
对于更复杂的数组,情况完全相同。以下都是相同的:
void g(Type p[][10][20]);
void g(Type (*p)[10][20]);
void g(Type p[10][10][20]);
void g(Type p[99][10][20]);
但是这些都不同于:
void g(Type p[][5][20]);
因为调整除了最外层数组维度以外的任何维度,都会影响(至少)最外层数组元素的大小,这意味着用于导航数组的指针算法必须更改。
int a[n][m]
是一个数组,其类型是长度为m
的int
数组。换句话说,数组的长度是其类型的一部分。对于所有函数参数,编译器都需要知道它的类型。int a[4]
和int b[5]
中,a和b是不同的类型。http://cplusplus.com/doc/tutorial/arrays/arrays3.gif
在内存中,二维数组看起来像这样:
char array[10][10]; // 0 - 99
正确:
// formal argument tells your compiler, that each column is 10 elements long
funca(int array[10][10]) {
// access to element 25 (2 * 10 + 4, the 10 is known through your formal argument, remember that an array is null based)
array[2][3] = 'x';
}
错误:
// formal argument tells your compiler, that ech colum is 5 elements long
funcb(int array[10][5]) {
// access to element 15 (2 * 5 * + 4, the 5 is known through your formal argument, remember that an array is null based)
array[2][3] = 'x';
}