A pointer is a variable that points to a location in memory.
int *pointer1;
int *pointer2 = pointer1;
Let’s say that both variables are pointing to memory location
0xA
Then I perform
pointer2++;
Now, pointer2 points to
0xB
Because both addresses point to the same place, I fully expect pointer1 to point to
0xB
But it does not. pointer1 still points to 0xA.
How is this possible? Does the pointer have another address to specify which pointer it actually is? If yes, what is this second address called?
You are confusing the value stored in the pointer with the value to which the pointer points.
The two pointers, per se, are completely independent, they just happen to point to the same memory location. When you write
you are incrementing the value stored in
pointer2(i.e. address to which it points), not the value stored at the pointed location; beingpointerandpointer2independent variables, there’s no reason why alsopointershould change its value.More graphically:
Supposing that
varis stored at memory location 0x10, we’ll have this situation:Now we increment ptr2
(due to pointer arithmetic the stored address gets incremented of
sizeof(int), that here we assume being 4)Now
ptr2points to 0x14 (what’s there is not important in this example);ptr1is left untouched pointing to 0x10.(naturally both
ptr1andptr2have an address where they are stored, as any other variable; this is not shown in the diagrams for clarity)