2

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?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Roland
  • 7,525
  • 13
  • 61
  • 124
  • 2
    I do not understand where the confusion is - if `&a` is pointer to array of `int`, then *&a is array of `int`, which is of type pointer to `int`, which is the type of `p`. – Marek Fekete Sep 24 '16 at 13:36
  • 1
    Please don't add _post links_ in the question body. Any good answer will quote /cite references anyway. – Sourav Ghosh Sep 24 '16 at 13:41
  • 1
    Unary `*` is the inverse of unary `&`, so `*&a == a`, and therefore if `p = a` is legal (which it is), then so is `p = *&a`. – jamesdlin Sep 24 '16 at 13:42
  • "*`a` is of type pointer to `int`*", no `a` is an array, namely of type `int[10]`. – alk Sep 24 '16 at 16:35
  • @reproduktor: `*&a` is indeed an array of `int`, However, its type is `int[10]`, not a "pointer to `int`". Type `int[10]` *decays* to `int *` later in this context. – AnT stands with Russia Sep 25 '16 at 03:49
  • @AnT: You are of course right, I should have written 'decays to' rather than 'is of'. My bad. – Marek Fekete Sep 25 '16 at 08:39

2 Answers2

3

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    @Roland Well, the official doc is not _for free_. _Hint: Please do a google search with n1570, hope that helps_ :) – Sourav Ghosh Sep 24 '16 at 13:47
1

When *& comes together then it is not evaluated. p = *&a; is equivqlent to p = a;. * and & nullify the effects of each other.

haccks
  • 104,019
  • 25
  • 176
  • 264