-2

*p++ in general adds 1 to pointer then references. But printf is taking the value after just dereferencing while the pointer got increased then dereferenced.

#include<stdio.h>

int main()
{
    int a[] = { 10,20,30 };
    int *p = a;

    printf("%d\n", *p++);//this makes p point at 20 but prints 10
    printf("%d\n", *p);//prints 20
    printf("%d\n", a[0]);//prints 10

}

Can someone please explain why this is happening ?

Thanks in advance

1 Answers1

6

*p++ in general adds 1 to pointer then [de]references

No it doesn't.

You used postfix increment (the ++ is after the p) so the original value is provided, not the newly incremented value.

You're thinking of *++p.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055