Need to understand this part of code:

int main()
int firstvalue= 5, secondvalue= 15;
int * p1, * p2;
p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;
*p2 = *p1;
p1 = p2;
*p1 = 20;
cout<< "firstvalueis " << firstvalue<< endl;
cout<< "secondvalueis " << secondvalue<< endl;
system ("pause");
return 0 ;


Look what have i understood from this program .. but the output is different
1 -p1 = address of firstvalue p2= address of second value
2- firstvalue = 10
3- we have put value of 10 in second value
3- we have made address of first and second value same..(not sure)
4-we have changed first value to 20

2nd value is 20 .. i understood but what about 1st value.. why it has been changed? ? ? ?

but ans is different ...
p1 = &firstvalue; //means you have stored address of firstvalue in pointer p1
p2 = &secondvalue; //means you have stored address of secondvalue in pointer p2
*p1 = 10;  /* (*) is derefence operator use to access the contents of address stored in p1.
 in this statement you are changing or storing 10(content) at the address stored in p1
 i.e of firstvalue */
*p2 = *p1;  // assigning the content of p1 i.e 10 to p2(which points to secondvalue)//
p1 = p2;  // assigning the address stored in p2(i.e secondvalue) to p1//
*p1 = 20; // same as line 3 ut this time you have assigned address of secondvalue to p1 so it
 will assign 20 to secondvalue// 

Last edited on
nice but still could you tell me why the 1st value (*p1) remain 10 still why it dont change to 20 ??
p1 = p2; // assigning the address stored in p2(i.e secondvalue) to p1//

see in this statement you are assigning( or replacing the previous address) address stored in p2(i.e of secondvalue) to p1.

p1=p2; is same as p1=&secondvalue;
Last edited on
Olpers you are having a hard time understanding that you are no longer pointing to firstvalue(p1) and second value(p2) you are now pointing to second value(p1) and second value(p2).

Topic archived. No new replies allowed.