3
#include <stdio.h>

int main()
{
    char a[] = "hello";
    char *ptr = a;
    printf ("%c\n",*ptr++);//it prints character 'h'.
    printf ("%c\n",*ptr);//it prints character 'e'.
    return 0;
}

As I understand it: In the above code, in *ptr++ expression, both * and ++ have same precedence and operation will take place from right to left, which means pointer will increment first and deference will happen next. So it should print the character 'e' in the first printf statement. But it is not.

So my question is: Where will it store the incremented value (in, *ptr++) if it is not dereferencing that location in first printf statement?

ArjunShankar
  • 23,020
  • 5
  • 61
  • 83
nagaradderKantesh
  • 1,672
  • 4
  • 18
  • 30

5 Answers5

8

ptr++ means "increment ptr, but return the pre-increment value."

Thus despite the fact that the increment happens first, it is the original, non-incremented pointer that is being dereferenced.

By contrast, if your precedence reasoning is correct, *++ptr should print e as you expect. ++ptr means "increment ptr and return the post-increment value".

Rawling
  • 49,248
  • 7
  • 89
  • 127
0

Whatever happens is correct.

When doing *ptr ++ it just takes the *ptr value and performs operation as it is a post increment and had you used ++ *ptr it would have printed e in the very first place.

0

p++ is post increment while ++p is pre increment. p++ gives the values of p and then increments the contents of p while ++p increments the contents of p and then returns the value of p

mujjiga
  • 16,186
  • 2
  • 33
  • 51
0

It will be stored in the pointer ptr itself. It is like making the ptr point to the next byte that it used to point:

ptr = ptr + 1;
nick.katsip
  • 868
  • 3
  • 12
  • 32
  • ptr = ptr + 1 means Pointer is incremented means pointing to next location and deference of that (ptr = ptr + 1) location is 'e' na, then why it is giving 'h' only in first printf statement – nagaradderKantesh Dec 20 '12 at 12:15
  • Because the increase by 1 byte is done after the execution of printf. – nick.katsip Dec 20 '12 at 13:42
-2

yupp, pointer will be autoamticaly incremented after each use.

Azzy
  • 433
  • 2
  • 18
  • 1
    The question is rathen "when" it will be incremented. In layman's terms `++i` means first increment, then return, while `i++` means first return value, then increment. – devsnd Dec 20 '12 at 12:03
  • "after each use"? seriously? – anishsane Dec 20 '12 at 12:32