Input:
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 by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
Output:
firstvalue is 10
secondvalue is 20
What I get from it:
p1 = address of first value
p2 = address of second value
value pointed by p1 (firstvalue) = 10
value pointed by p2 (secondvalue) = value pointed by p1 (firstvalue) = 10
or
simply secondvalue = firstvalue = 10
now both firstvalue and secondvalue are equal to 10
the address of second value (which is p2) copied to the address of firstvalue (which is p1)
suppose .....
at 1774 is p1 (10) and...
at 1776 is p2 (10)
now p1 should be at 1776 = 10 ... HOWEVER ... firstvalue remains 10
and value pointed by p1 (firstvalue) = 20 which is now at 1776????
print the value of firstvalue that is 10
print the value of secondvalue but how is it 20? The value of p2 hasn't changed! And second value has not been changed from 15 anywhere!
Could anyone parse this code?