I can’t understand what happens after line *p1=10, what happens with *p2 variable, and in the end how does secondvalue variable gets 20.
#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 << '\n';
cout << "secondvalue is " << secondvalue << '\n';
return 0;
}
Output of command
firstvalue is 10
secondvalue is 20
I can’t understand how the secondvalue variables gets a value of 20.
If we assigned *p2=*p1 mustn’t secondvalue variable get 10?
>Solution :
p1 = p2;
This doesn’t copy the value pointers point to, just "address" the p2 points to. Thus at this point both p1 and p2 point to the secondvalue, and changing either of them applies changes to the secondvalue