C++

XML, Perl, Python, and other languages can be discussed here, even if it isn't PHP (We might forgive you).

Moderator: General Moderators

Post Reply
littlecoder
Forum Commoner
Posts: 26
Joined: Fri Oct 17, 2008 4:36 am

C++

Post 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?
User avatar
Apollo
Forum Regular
Posts: 794
Joined: Wed Apr 30, 2008 2:34 am

Re: C++

Post 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.
littlecoder
Forum Commoner
Posts: 26
Joined: Fri Oct 17, 2008 4:36 am

Re: C++

Post by littlecoder »

Hi ,
Thanks Apollo for the reply
Post Reply