int x = 5;
int *p = &x;
printf("%u\t%u\n",&x,p);
printf("%d\n",*(p++));
printf("%d\n",*p);
Can someone help me understand the pointer arithmetic? And what will be the output?
After you increased ptr
, it's no longer pointing anywhere valid. Dereferencing the pointer with *ptr
leads to undefined behavior.
It might be simpler to understand if you consider &x
to be an array of a single element, and the initialization of p
(or ptr
, whichever you really picked) makes p
point to the first (and only) element of that array. By increasing p
it will be pointing out of bounds of that single-element array.
To visualize it, lets draw it out...
First you have
int x = 5;
which can be drawn as
+-------+ | x (5) | +-------+
Now we define and initialize the pointer to that:
int *p = &x;
So now it will look like this:
+-------+ | x (5) | +-------+ ^ | +---+ | p | +---+
The variable p
is pointing to the variable x
(the "up-arrow" in the illustration above).
If you then increase the pointer:
p++;
then it will look like this:
+-------+---- | x (5) | ??? +-------+---- ^ | +---+ | p | +---+
The pointer is no longer pointing to x
. What it points to is unknown, and the value at that location is also unknown.
So to answer the question about what is printed and why, we can't say.
Undefined behavior (UB for short) often isn't predicable, and there might be no way to tell what will happen.