Search code examples
carrayspointersassignment-operator

Assigning *&array to a pointer


The following excerpt is from Harbinson, Steele C: A Reference Manual (5th Edition). According to the book the two assignments to p are equivalent.

7.5.6 Address Operator

int a[10], *p;
p = a; p = *&a;

Yet, according to the C faq Question 6.12 a is of type pointer to int whereas &a is of type pointer to array of int.

So we should get a type error in the second assignment p = *&a because we are trying to assign an array of int to a pointer.

Why is the assignment p = *&a correct?


Solution

  • Quoting C11, chapter §6.5.3.2, Address and indirection operators,

    The unary * operator denotes indirection. [....] If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. [....]

    So, for p = *&a;,

    • &a is a pointer to "array of ints".
    • *&a is an array type.

    Now, when used in RHS of assignment, an array type decays to pointer to the first element of the array, an int *.

    Quoting C11, chapter §6.3.2.1

    Except when it is the operand of the sizeof operator, the _Alignof operator, or 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. [...]

    Hence, there's no warning/ error reported.