I´ve found this piece of code, which uses a pointer to a structure made by a compound literal:
int main()
{
struct s {int i; int x;} *p;
int j = 0;
p = &((struct s){ j++ });
}
My questions are:
j++
a valid expression for modifying i
and/or x
and to what it get evaluated?i
or x
? Pointer offsets of p
?In a compound literal, any unspecified members get default-initialized, just like an initializer list for an object. So
(struct s){ j++ })
is equivalent to
(struct s){ j++, 0 })
j++
is the old value of j
before j
is incremented, just as in any other assignment. So this will set p->i = 0
and j = 1
.
You can access the members using pointer dereferencing.
int x = p->x;
int i = p->i;