Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Inspired this quiestion .

Why does -

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

and

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

?

like image 947
URL87 Avatar asked Dec 12 '22 09:12

URL87


1 Answers

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.

like image 197
Sergey Kalinichenko Avatar answered Dec 15 '22 00:12

Sergey Kalinichenko