C++ pointers on example
- by terence6
I have a sample code :
#include <iostream>
#include <conio.h>
using namespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue;
p2 = &secondvalue;
cout << "1.p1: " << p1 << ", p2: " << p2 << endl;
cout << "1.*p1: " << *p1 << ", *p2: " << *p2 << endl;
*p1 = 10;
cout << "2.p1: " << p1 << ", p2: " << p2 << endl;
cout << "2.*p1: " << *p1 << ", *p2: " << *p2 << endl;
*p2 = *p1;
cout << "3.p1: " << p1 << ", p2: " << p2 << endl;
cout << "3.*p1: " << *p1 << ", *p2: " << *p2 << endl;
p1 = p2;
cout << "4.p1: " << p1 << ", p2: " << p2 << endl;
cout << "4.*p1: " << *p1 << ", *p2: " << *p2 << endl;
*p1 = 20;
cout << "5.p1: " << p1 << ", p2: " << p2 << endl;
cout << "5.*p1: " << *p1 << ", *p2: " << *p2 << endl;
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
cout << "firstvalue is " << &firstvalue << endl;
cout << "secondvalue is " << &secondvalue << endl;
getch();
return 0;
}
And here's the output :
1.p1: 0041FB40, p2: 0041FB34
1.*p1: 5, *p2: 15
2.p1: 0041FB40, p2: 0041FB34
2.*p1: 10, *p2: 15
3.p1: 0041FB40, p2: 0041FB34
3.*p1: 10, *p2: 10
4.p1: 0041FB34, p2: 0041FB34
4.*p1: 10, *p2: 10
5.p1: 0041FB34, p2: 0041FB34
5.*p1: 20, *p2: 20
firstvalue is 10
secondvalue is 20
firstvalue is 0041FB40
secondvalue is 0041FB34
What is copied in the line "p1 = p2" ? Does p1 become reference to p2 or does it work in different way ?