Search code examples
cpointerspostfix-operator

Why doesn't this program print '4'?


Shouldn't ptrj value be 4 after the execution of *ptrj++?

int j=3,*ptrj = NULL;
ptrj = &j;
*ptrj++;
printf("%i",*ptrj);

Solution

  • *ptrj++ is the same as *(ptrj++). What you expect is instead (*ptrj)++. You should look up operator precedence to learn more about which operators that acts before others. To understand what ptrj++ does, you should read about pointer arithmetic. But here is a quick explanation:

    • *(ptrj++) returns the value that ptrj points to (3), and THEN increments ptrj to point to the next value.

    • (*ptrj)++ returns the value that ptrj points to (3), and THEN increments the value that ptrj points at from 3 to 4.

    This means that what you're printing is the value at address &j + 1, which is the value that lies right after the variable j in memory. and this is undefined behavior. As Sourav pointed out, you would get a warning that points you to this if you enable compiler warnings.

    The only difference between *ptrj++ and ptrj++ is what it is returning. And since you don't use the return value, your code is equivalent to:

    int j=3,*ptrj = NULL;
    ptrj = &j;
    ptrj++;
    printf("%i",*ptrj);