padawan
padawan

Reputation: 1315

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?

Upvotes: 1

Views: 127

Answers (3)

John Bode
John Bode

Reputation: 123458

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.

Upvotes: 3

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

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

Upvotes: 0

gnasher729
gnasher729

Reputation: 52538

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.

Upvotes: 7

Related Questions