Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array as a parameter

Tags:

c++

I read in a book that, int f (int P[2][4]) cannot accept A[2][3], but B[3][4] is fine. what is the reason for this? Especially when we create dynamic allocation using pointers, this should not be a problem. Thanks

like image 398
Frustrated Coder Avatar asked Dec 16 '22 16:12

Frustrated Coder


2 Answers

The reason is that int f( int P[2][4] ); is a synonym for int f( int (*P)[4] ); The first dimension in a function declaration is just comments.

like image 110
James Kanze Avatar answered Jan 08 '23 13:01

James Kanze


The reason is that function parameters never really have array type. The compiler treats the declaration

int f(int P[2][4]);

as though it really said

int f(int (*P)[4]);

P is a pointer to an array of four ints. The type int [3][4] decays to that same type. But the type int [2][3] decays to the type int (*)[3] instead, which is not compatible.

Dynamic allocation is another matter entirely, and it probably does not involve array-of-array types no matter how you do it. (Array of pointers, more likely.)

like image 45
aschepler Avatar answered Jan 08 '23 13:01

aschepler