Basic in Pointers

hi,
i am new to programming..
i have a code..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

using namespace std;

int main()
{
    int x,y,*p1,*p2;
    p1 = &x;
    p2 = &y;
    *p1 = 10;
    *p2 = *p1;
    p1=p2;
    *p1=20;
    cout << " the value of x is " <<x << endl;
    cout << "the value of y is " <<y << endl;
    return 0;
}

I get the output as x = 10 and y = 20..but should not x =20 and y = 20 be the
correct answer...please help..
Oke, lets see what your code is doing:
1
2
3
4
5
6
    p1 = &x;     //p1 is pointing to x
    p2 = &y;     //p2 is pointing to y
    *p1 = 10;   //the value pointed by p1, x, is 10
    *p2 = *p1; //the value pointed by p2, y, is equal to the value pointed by p1, x: 10
    p1=p2;       //p1 is pointing to the same memory as p2: y
    *p1=20;     //the value pointed by p1, y, is 20: x is unchanced 


Try to understand what your code is doing, then try to solve it.
Hi Scipio,
Thanks a lot.. i am able to understand now...do you know of any
website offering pointer tutorials..because pointers are a little
difficult for me..
Thanks again
Hi Scipio,
thanks for the links...i will look into it...
Topic archived. No new replies allowed.