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,
Rocky2008

Recommended Answers

All 2 Replies

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:

  1. The address of the pointer object itself.
  2. The value of the pointer, which happens to be an address.
  3. The address of the pointed to object.
  4. 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.

The whole *p++ vs. *++p vs. ++*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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.