0

Hi, i am new to programming..
i have a code like

#include<iostream.h>
using namespace std;
int main()
{
int x,y;
int *p1,*p2;
p1=&x;
p2=&y;
*p1=10;
*p2=*p1;
p1=p2;
*p1=20;
cout<<  x << y;
return 0;
}

I do not understand it.. output is x =10 and y=20.. But both x and y should be 20 is it not ? pls help...

4
Contributors
4
Replies
5
Views
9 Years
Discussion Span
Last Post by Narue
0
#include<iostream>
using namespace std;
int main()
{
int x,y; 
int *p1,*p2;
p1=&x;
p2=&y; 
*p1=10;
*p2=*p1;
p1=p2;
*p1=20;
cout<<  x << y;
return 0;
}

I believe where you are getting confused is at line 11. There you tell it that the address that p2 holds is to be set to p1 . Now they ( p1 and p2 ) both point to y . Next you change the value of what p1 points to, which is y . Once you do p1=p2 , you no longer have a pointer to x , as both pointers point to the same place.

Hope that this helps!!

mattwaab;

0

>iostream.h is depreceated
No, deprecated means that it's still a part of the standard, but not recommended because it may be removed in the next revision. iostream.h was never a standard C++ header.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.