The pointer does not have the same address as
a
. For starters, you don't know the address of the pointer because nowhere in your code do you display it.
Even so, I know that the pointer does not have the same address as
a
, because the pointer is one object and
a
is a different object. Two different objects will have two different addresses.
Let's go through the code line by line and see what's happening.
int a = 5;
Create an int object, named
a
. Set the value of this object to 5. This object will be in some memory somewhere. For example, it might be in memory location 0x12341234. If we looked in that memory location, we would see the number 5.
int b = 8;
Create an int object, named
b
. Set the value of this object to 8. This object will be in some memory somewhere. For example, it might be in memory location 0x43214321. If we looked in that memory location, we would see the number 8.
const int* ptr =&a;
Create an int-pointer object, named
ptr
. This int-pointer will have an address; it exists somewhere in memory. Also, set the
value of this int-pointer to the memory address of a. This does not change the memory address of the int-pointer; it changes the
value of the int-pointer. If you looked at the int-pointer, wherever it is in memory, you would see the number 0x12341234 (using our example location of
a
from above)
ptr = &b;
Now change the
value of the int-pointer. Set its value to the memory address of
b
. Using our example locations,
ptr
now has the
value 0x43214321. The int-pointer itself is in the same place in memory; it just now stores a different value.
So the int-pointer was storing one memory address (the address of
a
), and then we
changed what the int-pointer was storing, and made it store the memory address of
b
.
why does the pointer have the same adress a a while its referencing is to b? |
It doesn't. Why do you think it does?