#include <iostream>
usingnamespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed to by p1 = 10
*p2 = *p1; // value pointed to by p2 = value pointed to by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "firstvalue is " << firstvalue << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
Output:
firstvalue is 10
secondvalue is 20
I don't understand how firstvalue prints 10 and secondvalue prints 20.
Shouldn't firstvalue be 20 because in the end *p1 = 20 and secondvalue be 10 because *p2 = *p1 while *p1 = 10?
after initialisation
------------------
firstvalue: has address 0x7fff27c1abbc value 25
secondvalue: has address 0x7fff27c1abb8 value 15
p1: points to 0x7fff27c1abbc value 25 (points to firstvalue)
p2: points to 0x7fff27c1abb8 value 15 (points to secondvalue)
after *p1 = 10
------------------
firstvalue: has address 0x7fff27c1abbc value 10
secondvalue: has address 0x7fff27c1abb8 value 15
p1: points to 0x7fff27c1abbc value 10 (points to firstvalue)
p2: points to 0x7fff27c1abb8 value 15 (points to secondvalue)
after *p2 = *p1
------------------
firstvalue: has address 0x7fff27c1abbc value 10
secondvalue: has address 0x7fff27c1abb8 value 10
p1: points to 0x7fff27c1abbc value 10 (points to firstvalue)
p2: points to 0x7fff27c1abb8 value 10 (points to secondvalue)
after p1 = p2
------------------
firstvalue: has address 0x7fff27c1abbc value 10
secondvalue: has address 0x7fff27c1abb8 value 10
p1: points to 0x7fff27c1abb8 value 10 (points to secondvalue)
p2: points to 0x7fff27c1abb8 value 10 (points to secondvalue)
after *p1 = 20
------------------
firstvalue: has address 0x7fff27c1abbc value 10
secondvalue: has address 0x7fff27c1abb8 value 20
p1: points to 0x7fff27c1abb8 value 20 (points to secondvalue)
p2: points to 0x7fff27c1abb8 value 20 (points to secondvalue)