Accessing field of NULL pointer to a struct works if address-of is used

133 Views Asked by At

I've just encountered a VERY weird thing:

I have a struct, say:

typedef struct {
int x;
} STRUCT;

[I know I can just say struct STRUCT without the typedef :)]

and a pointer STRUCT *p = NULL;

Suppose this pointer is (still) null at the time I execute this inside a function:

int *a = &p->x;

Why does this actually work? But this: int a = p->xgives a nullptr error?

EDIT: As far as I've read, the '->' operator has higher precedence than address-of (&).

0

There are 0 best solutions below