简体   繁体   中英

C Programming - Pointers (with increments)

int main()
{
    int x = 30, *y, *z;
    y = &x; 
    /* Assume address of x is 500 and integer is 4 byte size */
    z = y;
    *y++ = *z++;
    x++;
    printf("x=%d, y=%d, z=%d\n", x, y, z);
    return 0;
}

The above is the code. The output is: x=31, y=504, z=504

Please correct me if I'm wrong:

From what I understand: y=&x; assigns the address of x to y . So, y now holds the value of 500 .

z=y; Since y = 500 , this assigns 500 to z .

What really confuses me is this part *y++=*z++; , I don't exactly know what this means as there's many things going on at the same time. z gets incremented and pointed to somewhere (AND where is it pointing actually? There is no address assigned to it like y ie y=&x; . Then *y also gets incremented at the same time (are you even allowed to do that?).

Another thing that confuses me is that: in my opinion, since y points to x , when y++ happens, x should be incremented to 31 , and then when going down the code block x++ happens, x should now be 32 .

So, question is, how did we get that output of x=31, y=504, z=504 ? Thank you.

Let's break it down.

  • int x=30, *y, *z; y,z are defined and x is initialized.
  • y=&x; z=y; both of the pointers are assigned with the address of x (ie &x )
  • *y++=*z++; This one contains a few things, so I'll split it up:

  1. According to this the postfix++ takes precedence over indirection* so we can look at *y++ as *(y++)
  2. y++ means that the value of y will be incremented by 1 and since y is int* it will actually add sizeof(int) to it's value [4 in your case]. But the value of the expression y++ is the value of y before the increment, which leads us to...
  3. indirection: after the postfix++ is done, the indirection is evaluated and since y++ 's value is the value of "old" y you get the value of x

Conclusion: y was incremented by 1 but the indirection (dereference) led us to x.

The same applies to z . Eventually what happens is that both y,z are incremented, but before that the value in x is assigned to x (obsolete :) )

Next you'll have x++; which increments the value of x by 1. And that's it.

You can think of *y++=*z++; as:

  1. *y = *z;
  2. y++, z++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM