I am getting the wrong output when trying post-increment operation on a pointer in C

63 Views Asked by At

I am testing out pre- and post-increment on an array using pointer. I use the pointers p and q to access the elements of the array but the issue stems from the last result on pointer p.

#include <stdio.h>

int main(void)
{
        int a[] = {10, 11, -1, 56, 67, 5, 4};
        int *p, *q;
        p = a;
        q = &a[0] + 3;
        printf("%d, %d, %d\n", (*p)++, (*p)++, *(++p));
        printf("%d\n", *p);
        printf("%d\n", (*p)++);
        printf("%d\n", (*p)++);
        q--;
        printf("%d\n", (*(q + 2))--);
        printf("%d\n", *(p + 2) - 2);
        printf("%d\n", *(p++ - 2) - 1);
}

This is the output I get, I made the wrong output I am having bold:

12, 11, 11
13
13
14
67
54
**22025**

I am supposed to get the result 0 printed on the last printf statement in the code when I run it since after the previous lines of code p should be on the fourth element i.e. a[3] on the array, if p increments to a[4] then goes backward twice to a[2] (from the expression p++ - 2) then de-referenced and 1 is subtracted from the value, the final value should be 0 but I get a garbage value every time I run it. Can someone explain what I am doing wrong or why I am getting such value?

1

There are 1 best solutions below

3
John Bollinger On

Can someone explain what I am doing wrong or why I am getting such value?

Yes.

if p increments to a[4] [...]

But p does not get incremented to point to a[4]. The value of p is incremented only twice during the whole program. Once here:

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

, with the ++p, and once here:

        printf("%d\n", *(p++ - 2) - 1);

, with the p++.

You also have several appearances of (*p)++, but, as the parentheses direct, the object that is incremented in those cases is the one to which p points, not p itself. You have a p + 2, too, but that does not modify anything.

However, when the expression *(p++ - 2) - 1 is evaluated, only one of those increments has yet been applied, and although p++ performs another increment, it evaluates to the value of p prior to that increment, which points to a[1]. Under those circumstances, p++ - 2 has undefined behavior on account of attempting to compute an address outside the bounds of array a, on which p is based.

And as long as we're on UB, note well that this ...

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

... also has UB. In this case, it's because the side effect of ++p on the value of p is unsequenced with the evaluations of p in the two appearances of (*p)++, and because the side effects of those two appearances of (*p)++ are unsequenced relative to each other (either one of those causes would have been sufficient, so extra credit for you!). Surprising results are possible; inconsistent results are likely from implementation to implementation, and in principle, anything within the computer's ability could happen.