Page 1 of 1

C++

Posted: Sat Jan 24, 2009 12:26 am
by littlecoder
Hi,
I have just started C++
i have two pointeers *p1 and *p2.
int x,y;
int *p1,*p2;
p1=&x;
p2=&y;
*p1=100;
*p2=*p1;
p1=p2;
*p1=20;
When i run the program i get x =100 and y = 20..
I don't understand it..
both x and y need to have the value of 20.. isn't it so?

Re: C++

Posted: Sat Jan 24, 2009 4:55 am
by Apollo
littlecoder wrote:both x and y need to have the value of 20.. isn't it so?
No, x=100 and y=20 is correct.

With p1=p2 you copy the address that p2 pointed to, to p1. So p1 and p2 now both point to the same address, that of y. Now it doesn't matter if you do *p1=20 or *p2=20, both will change just y. No pointer points to x anymore.

Re: C++

Posted: Fri Jan 30, 2009 1:26 am
by littlecoder
Hi ,
Thanks Apollo for the reply