Why does 2 dimension array passing to function requires its size?

匿名 (未验证) 提交于 2019-12-03 02:31:01

问题:

Inspired this quiestion .

Why does -

void display(int p[][SIZE]) // allowed 

and

void display(int p[][]) // not allowed 

?

回答1:

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] 

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> 

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:

Because a 2D array is stored row wise and hence the function needs the number of columns so that it knows when the next row begins.



回答3:

That's because caculations in pointers requires that. When p points to 2 dimentional array that's size is SIZE this operation p+=3 is calculated this way:

if the value of p is a constant equal ADRESS p receive this value ADRESS + 3*SIZE.

That's because arithmitic in pointers is different from arithmitic in real numbers. This calculation can't be done without knowing the size of the array.



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