I have a question about the behavior of the address-of operator followed by a dereference operator.
Let's take a look at the expression &*p
where p
is of type int *
.
The C11 standard (section 6.5.3.2) says:
The unary & operator yields the address of its operand. If the operand has type ‘‘ type ’’, the result has type ‘‘pointer to type ’’. If the operand is the result of a unary * operator, neither that operator nor the & operator is evaluated and the result is as if both were omitted, except that the constraints on the operators still apply and the result is not an lvalue.
With the footnote:
Thus, &*E is equivalent to E (even if E is a null pointer), and &(E1[E2]) to ((E1)+(E2)). It is always true that if E is a function designator or an lvalue that is a valid operand of the unary & operator, *&E is a function designator or an lvalue equal to E. If *P is an lvalue and T is the name of an object pointer type, *(T)P is an lvalue that has a type compatible with that to which T points. Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime.
It is clear that &*p
has to be equal to p
except that &*p
is not an lvalue.
If we now consider a
with type int[10]
, what type is &*a
?
And should there be a difference between for example sizeof a
and sizeof &*a
?
On the one side if we evaluate &*a
, a
would decay to int *
with the dereference operator it will become int
and with the address-of operator then int *
.
On the other side if &*a
behaves "as if both were omitted" the type should be int[10]
.
A short example reveals that gcc treats the expression different:
#include <stdio.h>
int main(void)
{
int a[10];
printf("%zu\n%zu\n", sizeof a, sizeof &*a);
return 0;
}
Output:
40
8
Is this in agreement with the C11 standard?
Maybe it is because the "constraints on the operators still apply" and the operand of the dereference operator has to be a pointer?
*a
has a type ofint
, so I would think&(int)anything
to returnint*
. – Eugene Sh.a
is an lvalue, but&*a
is not an lvalue. – Ian Abbottvoid *p = &a;
, but notvoid *q = &(&*a);
– chux - Reinstate Monica