I have the following piece of code.
int a = 10, b = 20;
int *x, *y, *z;
int **pp;
int arr[3] = { 5, 13, 29 };
x = &b;
pp = &y;
y = arr + 1;
*y = a;
z = y;
**pp = 999;
y++;
printf("%i %i %i %i %i %i %i %i %i", a, b, *x, *y, *z, **pp, arr[0], arr[1], arr[2]);
I expected the output would be 10 20 20 29 10 999 5 999 29
, however, the correct output appeared to be 10 20 20 29 999 29 5 999 29
. The differences are in *z
and **pp
. I can't understand why so, even though I tried to draw diagrams and analyze the result step by step. Why *z
and **pp
are 999 and 29, respectively, not 10 and 999? Thank you.
After this statement
y = arr + 1;
the pointer y
points to the second element of the array arr
,
So the second element is set to 10
after the next statement
*y = a;
And we have the following content of the array arr
{ 5, 10, 29 }
The pointer z also points to this second element
z = y;
However the second element was rewritten
**pp = 999;
because the dereferenced pointer pp
always yields the pointer y
. The content of the array now is
{ 5, 999, 29 }
and the pointer y
was incremented and after this statement
y++;
points to the third element of the array. Pay attention to that the pointer pp
still points to the pointer y
that stores now the address of the third element of the array.
The variables a
and b
were not changed> so the call of printf
outputs
10 20
the pointer x
points to the variable b
so we have
10 20 20
The pointer y
points to the third element of the array. So
10 20 20 29
The pointer z
points to the second element of the array because it has the value of the pointer y
before its increment.
10 20 20 29 999
The pointer pp
points to the pointer y
and as a result the expression **pp
yields the same value as the expression *y
10 20 20 29 999 29
And these expressions arr[0], arr[1], arr[2]
sequentially provide values of the array
10 20 20 29 999 29 5 999 29