为什么2维数组传递给函数需要它的大小? [英] Why does 2 dimension array passing to function requires its size?
问题描述
启发<一个href=\"http://stackoverflow.com/questions/9446707/correct-way-of-passing-2-dimensional-array-into-a-function\">this quiestion。
Inspired this quiestion .
为什么 -
void display(int p[][SIZE]) // allowed
和
void display(int p[][]) // not allowed
推荐答案
由于阵列衰减的的指针。如果你不提供阵列的第二个维度的基数,编译器不知道如何取消引用这个指针。
Because arrays decay to pointers when passed to a function. If you do not provide the cardinality of the second dimension of the array, the compiler would not know how to dereference this pointer.
下面是一个较长的解释是:当你写这个
Here is a longer explanation: when you write this
p[index]
编译器执行一些指针运算找到的元素,它需要引用地址:它乘以首页
按大小 P
的元素,并将其添加到基址 p
:
the compiler performs some pointer arithmetic to find the address of the element that it needs to reference: it multiplies index
by the size of p
's element, and adds it to the base address of p
:
address = <base address of p> + index * <size of p's element>
当你试图传递一个数组这样, P [] []
,编译器只知道 P $ C的基址$ C>,而不是它的元件的尺寸。这是为了让编译器知道
P
的元素,你需要提供第二个维度的基数大小。
When you try passing an array like this, p[][]
, the compiler knows only the base address of p
, but not the size of its element. It is in order for the compiler to know the size of p
's element that you need to provide the cardinality of the second dimension.
这篇关于为什么2维数组传递给函数需要它的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!