简体   繁体   中英

I cannot change the value of an integer using pointer

Here is the code I'm running:

#include <iostream>
using namespace std;

int main()
{
    int x = 5;
    int *p;
    p = &x;
    *p++;
    cout<<x<<endl;
    return 0;
}

The output should be 6, because p is pointing at the address of x . However, I get 5.

But more interestingly, I couldn't understand why the output is 6 when I change *p++ with *p = *p+1 . Why is this?

You are wrong. *p++ reads the value that p points to, then increases the pointer p. You probably wanted (*p)++.

*p = *p + 1 works because it is correct.

Postfix ++ has higher precedence than unary * , so *p++ is parsed as *(p++) ; IOW, you're incrementing the pointer, not the thing being pointed to.

Use (*p)++ to increment the thing being pointed to, or use ++*p .

Use brackets if you do not understand operator precedence.

*p++

is

*(p++)

and you want

(*p)++

The rule of thumb is:

  • multiplication and division go before addition and subtraction
  • for everything else, just use brackets

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