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
pointer2++;
you are incrementing the value stored in pointer2
(i.e. address to which it points), not the value stored at the pointed location; being pointer
and pointer2
independent variables, there's no reason why also pointer
should change its value.
More graphically:
int var=42;
int * ptr1 = &var;
int * ptr2 = ptr2;
Supposing that var
is stored at memory location 0x10, we'll have this situation:
+----------+
| | 0x00
+----------+
| | 0x04
+----------+
| | 0x08 +------------+
+----------+ +------| ptr1: 0x10 |
| | 0x0C | +------------+
+----------+ | +------------+
| var: 42 | 0x10 <----+------| ptr2: 0x10 |
+----------+ +------------+
| | 0x14
+----------+
| | 0x18
+----------+
| |
Now we increment ptr2
ptr2++;
(due to pointer arithmetic the stored address gets incremented of sizeof(int)
, that here we assume being 4)
+----------+
| | 0x00
+----------+
| | 0x04
+----------+
| | 0x08 +------------+
+----------+ +------| ptr1: 0x10 |
| | 0x0C | +------------+
+----------+ | +------------+
| var: 42 | 0x10 <----+ +--| ptr2: 0x14 |
+----------+ | +------------+
| | 0x14 <--------+
+----------+
| | 0x18
+----------+
| |
Now ptr2
points to 0x14 (what's there is not important in this example); ptr1
is left untouched pointing to 0x10.
(naturally both ptr1
and ptr2
have an address where they are stored, as any other variable; this is not shown in the diagrams for clarity)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With