简体   繁体   中英

C - Increment and decrement pointer, then retrieve value

The following code outputs y as a massive integer, not 15 . I don't understand why. I know the -- and ++ operators come before the * operator, so it should work.

What the follwing code is trying to say.

/*
Create a variable, set to 15.
Create a pointer to that variable.
Increment the pointer, into undefined memory space.
Decrement the pointer back where it was,
then return the value of what is there,
and save it into the  variable y.
Print y.    
*/

int main()
{
    int x = 15;
    int *test = &x;
    test++;
    int y = *test--;
    printf("%d\n", y);

    return 0;
}

If instead, I change the code to the following:

int main()
{
    int x = 15;
    int *test = &x;
    test++;
    test--;
    printf("%d\n", *test);

    return 0;
}

That code outputs 15 . Why?

The difference is between x++ and ++x , post- and pre-increment of a pointer.

  • When ++ is after x , the old value is used prior to the increment
  • When ++ is before x , the new value is used after the increment.

This will work:

int y = *(--test);

Although parentheses are not necessary, it is a good idea to use them for clarity.

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