Hello could someone answer my Q for the code below: | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Hello could someone answer my Q for the code below:

int main() { int v1=5; int v2=15; int*p1; int*p2; p1=&v1; p2=&v2; *p1=10; *p2=*p1; p1=p2; *p1=20; cout<<"1st v is "<<v1<<endl; cout<<"2nd v is "<<v2<<endl; i just cant get why (v2)'s value will be 20 while we changed *p1 to 20 ?? thanks

18th Jan 2018, 8:30 PM
RiGeL
RiGeL - avatar
4 Answers
+ 5
it assigns p2 address to p1 since both are ptrs. So when given value 20 it assigns it to v2 which is address of p2
18th Jan 2018, 8:51 PM
Michael Simnitt
Michael Simnitt - avatar
+ 3
@Michael thank you but how about the role of p1=p2 here?
18th Jan 2018, 8:38 PM
RiGeL
RiGeL - avatar
+ 3
@Michael thank you alot ,its clear now
18th Jan 2018, 8:53 PM
RiGeL
RiGeL - avatar
+ 2
*p2=*p1 -assigns ptr p1 value to p2 which is using address of v2
18th Jan 2018, 8:34 PM
Michael Simnitt
Michael Simnitt - avatar