1

I am new to C programming and have been looking for this question for few days...

int arr[][2]={11,22,33,44,55,66};
int (*ptr)[2]=&arr[1];    //line a
int (*ptr1)[2]=arr[1];    //line b

For line (a) compiler has no issue but for line (b) it gives ERROR-cant convert int* to int[2]*

Now both &arr[1] and arr[1] have same size(when I checked in sizeof operator).

So please help me understand what exactly is happening? what is the difference between arr[1] and &arr[1]? Thank you!

Jay
  • 9,585
  • 6
  • 49
  • 72
Suraj
  • 415
  • 2
  • 6
  • See here, it should help: http://stackoverflow.com/questions/2094666/pointers-in-c-when-to-use-the-ampersand-and-the-asterisk – pez Sep 26 '14 at 01:52

1 Answers1

2

"same size" does not mean "same type". There are various types with the same size.

arr[1] has type int[2] . So &arr[1] has type int(*)[2], so line a is fine.

When you use an expression with array type and it is not the operand of & or sizeof, it undergoes lvalue-to-rvalue conversion, and the result of this conversion is a pointer to the first element of the array. (This is sometimes called decay).

So on line b, after decay, arr[1] is the same as &arr[1][0] which as type int *. This is incompatible with int (*)[2] so that assignment fails.

The definition of compatible type for pointers is (paraphrased) that the type is identical. Any assignment between non-compatible pointers other than void * requires a cast (and probably doesn't do what you expect).

For further reading check the C FAQ and perhaps also search this site for highly-rated questions on the topic.

M.M
  • 138,810
  • 21
  • 208
  • 365