Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this declaration not work

Tags:

c

pointers

In int (*x)[10]; x is a pointer to an array of 10 ints

So why does this code not compile:

int arr[3] ;

int (*p)[3] =arr;

But this works:

int  arr[3];

int (*p)[3] =&arr;
like image 620
Expert Novice Avatar asked Sep 08 '11 14:09

Expert Novice


1 Answers

arr is an expression that evaluates to an int* (this is the famous 'arrays decay to pointer' feature).

&arr is an expression that evaluates to a int (*)[3].

Array names 'decay' to pointers to the first element of the array in all expressions except when they are operands to the sizeof or & operators. For those two operations, array names retain their 'arrayness' (C99 6.3.2.1/3 "Lvalues, arrays, and function designators").

like image 130
Michael Burr Avatar answered Oct 06 '22 01:10

Michael Burr