How does sizeof work with this dereferencing of a pointer to array?

with int (*ptr)[4] = &arr ; you have a pointer to an array of four integers and pointing to arr.

ptr is now pointing to arr, like a double pointer. We can access elements of arr using ptr[0][x] where x could be 0 to 4.

So sizeof(ptr[0]) is same as sizeof(arr)


OP: ptr[0] points to the first element in the array.

Type confusion. ptr[0] is an array.

ptr is a pointer to array 4 of int.
ptr[0], like *ptr deferences the pointer to an array.
sizeof(ptr[0]) is the size of an array.


With sizeof(ptr[0]), ptr[0] does not incur "an expression with type ‘‘pointer to type’’ that points to the initial element of the array object" conversion. (c11dr §6.3.2.1 3). With sizeof, ptr[0] is an array.


By definition, ptr[0] is the same as *(ptr + 0) which in turn is the same as *ptr. Further, ptr is initialized with &arr, so *ptr is *&arr and that is just arr. Note that the intermediate storage of &arr in ptr does not perform any array decay, so the equivalence is maintained and no type information is lost.

Note that all this is computed at compile-time, just to avoid this additional pitfall.


ptr here is of type pointer to an array of 4 int elements and the array type has size 16 on your platform (sizeof(int) * (number of elemetns)).

I can't understand why using sizeof(ptr[0]) gives the size of the whole array 16 bytes not the size of only the first element 4 bytes

because C type system has array types. Here both arr and *ptr has it. What you declare that you have. To get sizeof int here you should sizeof(ptr[0][0]) - where ptr[0] evaluates to array.

Tags:

C

Arrays

Pointers