tags:

views:

130

answers:

2

i am using c pointers in which if i increment as *p++ it increments p but returns only the value which p pointed before it was incremented. how can i increment the value pointed by p.

+4  A: 

postfix ++ has a higher precedence than *, the compiler reads *p++ as *(p++). Since you want to increment the value of *p, you need braces: (*p)++ will return the value of *p and afterwards increment the value of p by one. ++(*p) will increment the value of *p and return this value then.

It is possible you omit the braces for the last case and write ++*p, but I'd suggest not to do it, because ++(*p) is the dual to (*p)++, but for ++*p it is not *p++.

Luther Blissett
-1 How has this got upvoted? The question asks how to increment the value pointed to by p, not how to increment p and then get the value pointed to by the new p.
JeremyP
-1. Neeraj is asking "how can i increment the value pointed by p." This increments the pointer `p` and then deferences it to get the value that `p` now points at.
Stephen
Ooops. This was a misread by me..I think my upvoters did the same :-). I'm fixing this.
Luther Blissett
Removed my down vote from the corrected answer.
JeremyP
Ditto for my downvote.
Stephen
thank you for suggesting me the solution i used (*P)++ and it worked.
Neeraj87
+5  A: 

do this: (*p)++

Using parenthesis, you've indicated you mean to increment the value pointed at.

Ian
If you dont need the value and like to excice unneeded parenthesis `++*p` should also work.
David X
+1. I don't understand why the other answers are voted up or at least not voted down. Ian's answer is the only correct one here. The asker of the question wishes to increment the value that p **points** at, not the value of p.
Stephen
@Stephen it's a slightly ambiguos question "it increments p" sounded like he really was trying to increment the pointer. On rereading I think this is the right answer though
cobbal
@Stephen: Sometimes answerer and upvoter read questions like the OP's and think "Oh, that thing again: He's got *p++ and now wants to increment the other way'. I got +3 for an answer that had nothing to do with OP's Q, so I'd say this happens easily.
Luther Blissett
@cobbal: It's not ambiguous at all. "it increments p" is describing the behaviour he is seeing. "how can I increment the value pointed [to] by p" is describing the behaviour wanted.
JeremyP
In fact, C's precedence rules are a frequent source of snags. A few extra parenthesis to clarify your intent are a good thing, and you should leave them in even if they seem redundant because redundancy is better than error.
Ian