can someone explain why the output of firstvalue
is 10 although it is manipulated at the end when writing *p=20
?
Thanks
Input
#include <iostream>
using namespace std;
int main(){
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;
*p2 = *p1;
p1 = p2;
*p1 = 20;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "p1 is " << p1 << endl;
cout << "p2 is " << p2 << endl;
cout << "*p1 is " << *p1 << endl;
cout << "*p2 is " << *p2 << endl;
return 0;
}
Output
firstvalue is 10
secondvalue is 20
p1 is 0x7ffc0589c4f4
p2 is 0x7ffc0589c4f4
*p1 is 20
*p2 is 20
CodePudding user response:
why the output of firstvalue is 10 although it is manipulated at the end when writing *p=20?
There is no *p=20
in the program.
There is *p1 = 20
which doesn't manipulate firstvalue
because p1
doesn't point to firstvalue
. It points to secondvalue
because of this assignment: p1 = p2
.
CodePudding user response:
With these istructions:
p1 = &firstvalue;
p2 = &secondvalue;
p1
points to firstvalue
, and p2
to secondvalue
.
The next two instructions:
*p1 = 10;
*p2 = *p1;
set the value pointed by p1
to 10, i.e., firstvalue
is set to 10, and the value pointed by p2
(secondvalue
) to the value pointed by p1
. So now firstvalue = secondvalue = 10
.
This istruction:
p1 = p2;
set the pointer p1
to p2
: now p1
points to secondvalue
. After that, this istruction
*p1 = 20
set the value of secondvalue
to 20, while firstvalue
is untouched.