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
2010-08-15 11:49:16
-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
2010-08-15 12:01:50
-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
2010-08-15 12:01:55
Ooops. This was a misread by me..I think my upvoters did the same :-). I'm fixing this.
Luther Blissett
2010-08-15 12:08:03
Removed my down vote from the corrected answer.
JeremyP
2010-08-15 12:39:07
Ditto for my downvote.
Stephen
2010-08-15 12:52:32
thank you for suggesting me the solution i used (*P)++ and it worked.
Neeraj87
2010-08-16 14:32:16
+5
A:
do this: (*p)++
Using parenthesis, you've indicated you mean to increment the value pointed at.
Ian
2010-08-15 11:55:41
If you dont need the value and like to excice unneeded parenthesis `++*p` should also work.
David X
2010-08-15 12:02:30
+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
2010-08-15 12:02:48
@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
2010-08-15 12:07:51
@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
2010-08-15 12:28:15
@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
2010-08-15 12:37:28
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
2010-08-15 14:08:32