Why can we omit the first dimension of a multidimensional array when we are passing it to a function

倖福魔咒の 提交于 2020-01-21 01:53:05

问题


Why can we omit the first dimension of a multidimensional array when we are passing it to a function?

In my programming class, we were told what when passing a multidimensional array to a function we can omit first dimension, for example, a[10][15][20] can be passed as a[][15][20].

Why?


回答1:


Because the array will decay to pointer and to calculate offset to the elements of the array you do not need to know the innermost dimension. Offset to a[i][j][k] is i*nj*nk+j*nk+k (where nj and nk are corresponding dimensions).




回答2:


You cannot pass arrays to functions. Any function declared as taking an array type is automatically adjusted to take the corresponding pointer type. When you use the name of an array in a function call expression it decays to a pointer to its first element.

These four declarations declare the same function:

void f(int b[10][15][20]);
void f(int (*b)[15][20]);
void f(int b[][15][20]);
void f(int b[100][15][20]);

and, given int a[10][15][20];, these function calls are identical:

f(a);
f(&a[0]);


来源:https://stackoverflow.com/questions/8205148/why-can-we-omit-the-first-dimension-of-a-multidimensional-array-when-we-are-pass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!