why deselect a pointer to an array of integers (in Table 2d) return (or unhook to) pointer to the first element?

advertisements

I have read many posts of pointers and 2d array relation, but I cant seem to understand concept. Lets say there is a 2d array int a[3][2] and an array int b[2].
now a is returning a pointer to array of integers of size 3. It would be of type int (*)[2].

As my understanding of the concept goes derefrencing it(*a) would give me the array itself and this decays to a pointer pointing to first element of the 1d array and is of type (int*) . now the bold part is the doubt.

why and how does this decay happen where the array itself(which is the complete 1d array a[0]) decays to first element of the 1d array?
(cant seem to get the why and how part) and cant seem to find it on other links also.

As a[0], *a,&a[0][0] represent the same pointer. here as a[0] is the first 1d array. then is this true that b(declared above) and a[0] represent the same thing (both being 1d array and then decay to the pointer to first element in array of type (int*)?


why and how does this decay happen where the array itself decays to first element of the 1d array?

C11: 6.3.2.1 p(3):

Except when it is the operand of the sizeof operator, the _Alignof operator 1,the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

In simple; the array names can be converted to pointer to its first element.

Since a is an array name, it decays to the pointer to its first element which is a 1D array. Its type is int(*)[2]. Since a (after decay) is a pointer to an array of 2 int, *a is an array of 2 ints. Since that's an array type, i.e *a is an array name for the first 1D array, it decays to a pointer to the first element (a[0][0]) of the array object. So, its type is int *.

is this true that b(declared above) and a[0] represent the same thing (both being 1d array and then decay to the pointer to first element in array of type (int*)?

Yes b and a[0] are both of type int * (after decay).


1. Read the commat by Keith Thompson. Also read this answer which states that: A draft of the C11 standard says that there's another exception for arrays, namely when the array is the operand of the new _Alignof operator. This is an error in the draft, corrected in the final published C11 standard; _Alignof can only be applied to a parenthesized type name, not to an expression.