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?
Yes.
But
pdoes not get incremented to point toa[4]. The value ofpis incremented only twice during the whole program. Once here:, with the
++p, and once here:, 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 whichppoints, notpitself. You have ap + 2, too, but that does not modify anything.However, when the expression
*(p++ - 2) - 1is evaluated, only one of those increments has yet been applied, and althoughp++performs another increment, it evaluates to the value ofpprior to that increment, which points toa[1]. Under those circumstances,p++ - 2has undefined behavior on account of attempting to compute an address outside the bounds of arraya, on whichpis based.And as long as we're on UB, note well that this ...
... also has UB. In this case, it's because the side effect of
++pon the value ofpis unsequenced with the evaluations ofpin 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.