Can anyone explain the difference between * ptr++ and ++ *ptr ?
To my understanding, * ptr++ increments the pointer and not the value pointed by it and ++ *ptr increments the value being pointed by it. Does the former mean incrementing the address of the pointer ? Please explain.
Thanks & Regards,
Start by writing a piece of code with two pointers and known contents.
Output the value of the pointers and the data that they point to.
Now, do both increments on the two pointers.
Next, output the value of the pointers and the data that they point to again.
Last, compare the outputs.
Does the former mean incrementing the address of the pointer ?
When pointers are involved there are four distinct values:
- The address of the pointer object itself.
- The value of the pointer, which happens to be an address.
- The address of the pointed to object.
- The value of the pointed to object.
Let's say you have this:
int i = 123; int *p = &i;
The value of the pointed to object is 123 and the value of the pointer is the address of
i. You can say &p to get the address of
p, which you'll take care to note is not the same thing as the value of
p; they're two distinct addresses referring to two different objects.
With that said, when you say
p++ you're incrementing the value of
p. It's still incrementing an address, but it's important to make the distinction between the address of a pointer and the address stored by a pointer.
++*p dealie is a matter of operator associativity (or precedence in the case of postfix increment). Postfix increment has higher precedence than indirection, so
*p++ is equivalent to
*(p++). Prefix increment and indirection have the same precedence, but their associativity is right to left, so the one further to the right will occur first. Therefore
*++p will increment the value of
p first, then dereference the new addres while
++*p will dereference
p first and as a result increment the value of the pointed to object.