Pointers

I'm really confused on how pointers work. Here is a sample program by my prof, im confused on what happened to the assigned values of "firstvalue" and "second value", and if p1 = to p2 shouldnt their values be also equal?



#include <iostream>
using namespace std;

int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue;
p2 = &secondvalue;
*p1 = 10;
*p2 = *p1;
p1 = p2;
*p1 = 20;

cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;

system("pause");
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
using namespace std;

int main ()
{
     int firstvalue = 5, secondvalue = 15;
     int * p1, * p2;
     p1 = &firstvalue;//p1 points to firstvalue
     p2 = &secondvalue;//p2 points to secondvalue
     *p1 = 10;//firstvalue=10
     *p2 = *p1;//secondvalue=firstvalue(secondvalue=10)
     p1 = p2;//p1 points to secondvalue
     *p1 = 20;//secondvalue is 20
     cout << "firstvalue is " << firstvalue << endl;
     cout << "secondvalue is " << secondvalue << endl;
     system("pause");
     return 0;
}
1
2
3
4
5
6
7
8
p1 = &firstvalue; // p1 points to firstvalue.
p2 = &secondvalue; // p2 points to secondvalue.
*p1 = 10; // p1 points to firstvalue so this will set firstvalue to 10.
*p2 = *p1; // p2 points to secondvalue and p1 points to firstvalue so 
           // this is the same as writing secondvalue = firstvalue; which
           // makes secondvalue contain the value 10.
p1 = p2; // This makes p1 point to whatever p2 is pointing to. That is secondvalue.
*p1 = 20; // p1 is pointing to secondvalue so this will set secondvalue to 20. 
Topic archived. No new replies allowed.