Tuesday 26 April 2016

Pointer to a 2D array in C




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!


Answer



"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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...