I have this code in c++.
#include<iostream>
using namespace std;
int main()
{
int z;
int v1,v2;
int *p1,*p2;
p1 = &v1;
p2= &v2;
*p1 = 15; // value pointed by p1 is 10
*p2 = *p1; // value pointed ny p2 is the value pointed by p1 which at the moment is 10.
p1 =p2; //p1 is assigned the value of p2 which is 10
*p1 = 20; // the value pointed by p1 is 20;
cout<<"v1:"<<v1<<endl;
cout<<"v2:"<<v2<<endl;
cin>>z;
}
Here the output is v1:15, v2:20.
I am little confused here, p1 points to address of v1,the latest value pointed by p1 is 20 not 15, so how come the output shows v1:15
With the output i assume that the value assigned immediately to the pointer after the pointer is pointing to the address of a variable counts rather than the latest value.Is that correct?
p2is&v2, not 10. Pointers hold addresses.