Search code examples
c++cpointerspointer-arithmetic

Output of C program involving pre/post increment and pointer


I was a solving guess output of following C code quiz, where I didnt get the output of below one:

(In comments following printfs I have written the execution sequence that I think that line has executed in and what confuses me)

    int i;
    int *ptr = (int *) malloc(5 * sizeof(int));
    int *ptr2 = ptr;
    int *ptr3 = ptr;

    for (i=0; i<5; i++)
    {
        *(ptr + i) = i;
    }
    printf("%d ", *ptr++);   //*ptr evaluated to 0, print 0, increment ptr 
    printf("%d ", (*ptr)++); //*ptr evaluated to 1, print 1, increment ptr
    printf("%d ", *ptr);     //*ptr evaluated to 2, print 2
    printf("%d ", *++ptr);   //increment ptr, *ptr evaluated to 3, print 3 (but in actual it prints 2, why?)
    printf("%d ", ++*ptr);   //*ptr evaluated to 3, increment 3, print 4 (but in actual it prints 3, why?)

Output

0 1 2 2 3

Why the last two integers 2 and 3? I felt they should be 3 and 4.

Here is ideone link.


Solution

  • *ptr++
    

    Increment ptr and then dereference the previous value of ptr, yielding ptr[0] (0).

    (*ptr)++
    

    Dereference ptr and then increment the value stored there, yielding ptr[1] (1) (but leaving it as 2).

    *ptr
    

    Dereference the pointer, yielding ptr[1] (2) because we still haven't moved on.

    *++ptr
    

    Increment ptr and dereference the new value of ptr, yielding ptr[2] (2).

    ++*ptr
    

    Dereference ptr and increment the stored value, yielding ptr[2] (3).

    In general the key to understanding problems like this is knowing operator precedence and associativity and applying that knowledge in combination with careful reading of the code. In this specific case the gotcha is step 3, where ptr is only dereferenced and not incremented.