user13290696
user13290696

Reputation:

How exactly does post increment of a pointer work?

This is my code

#include <stdio.h>
int main(void)
{
  int i, myarr[] = {15,3,27};
  int *ptr=&myarr[1];

  printf("%d\n",*ptr++);
  printf("%d\n",++*ptr);

  ptr=myarr;

  for(i=0;i<3;i++)
    printf("%d", *(ptr+i));

  return 0;
}

In the part where post-increment of a pointer is used, why is it not printing out 4, but 28?

output

3
28
15328

Upvotes: 0

Views: 49

Answers (2)

Eric Postpischil
Eric Postpischil

Reputation: 222244

In *ptr++, ++ has precedence over *, so the expression is *(ptr++). This takes the value of ptr, separately increments ptr, and uses the value from before the increment with *. Since before the increment, ptr points to the 3, *ptr++ evaluates to 3. The increment leaves ptr pointing to the 27.

In ++*ptr, the * must be applied first, so the expression is ++(*ptr). Then *ptr is the thing ptr points to, which is the 27, and ++ increments it and produces the value after the increment. So the 27 is changed to 28, and the value of the expression is 28.

Upvotes: 0

chux
chux

Reputation: 153303

printf("%d\n",*ptr++); points to 3, reads the 3, increments the pointer and returns the 3 to be printed.

ptr now points to 27

printf("%d\n",++*ptr); points to the 27, increments the 27 to 28 in the array, returns 28 to be printed. ptr unchanged.

Upvotes: 3

Related Questions