Accessing Structure Elements Using Pointers

I was surprised when the next program did not work.

typedef struct _x {
  int a;
  char b;
  int c;
} x;

main() {
  x *ptr = 0;
  char *d = &ptr->b;
}

According to my understanding, the operator ->has a higher priority over the operator &. Therefore, I expected the program to crash on the next statement when we try to dereference a NULL pointer tr.

char *d = &ptr->b; 

But the operator &ptr->bestimates the valid address. Can someone explain where I'm wrong?

+5
source share
4 answers

. C "" . C undefined, - . undefined -. . , "" . , -, .

undefined. , " ", , , . , , , ( , ).

+5

, , , . ,

&ptr->b

ptr ptr->b. , . , , - , b , ptr. 0, , , segfault.

+4

&ptr->b == sizeof(int), b _x _x.a ( int) *((x*)0). 4 ( 32- ) d. d, seg-fault.

+2

. &ptr->b " b , ptr". , .

. C ptr[5] *(ptr + 5), , &(ptr[5]) &(*(ptr + 5)). , & * "" (ptr + 5), , .

C makes this a bit cloudy because it distinguishes lvalues ​​from rvalues. That is, an expression related to memory is processed differently on the left side of the expression than on the right. Given a type operator x = y;, the C compiler will load the value from the address yand store it in the address x. This difference is: yimplicitly dereferenced, but xnot.

+2
source

All Articles