The purpose might become clearer when additional output is used:
// more pointers
#include <string>
#include <iostream>
using namespace std;
void print(string description, int value1, int value2, int *pointer1, int *pointer2) {
cout << description << ": " << endl;
cout << " first value is " << value1 << endl;
cout << " second value is " << value2 << endl;
cout << " first pointer is at " << pointer1 << " with value " << *pointer1 << endl;
cout << " second pointer is at " << pointer2 << " with value " << *pointer2 << endl;
cout << endl;
}
int main()
{
int firstvalue = 5;
int secondvalue = 15;
int * p1 = &firstvalue;
int * p2 = &secondvalue;
print("Initial values", firstvalue, secondvalue, p1, p2);
// value pointed by p1 = 10
*p1 = 10;
print("After setting *p1 to 10", firstvalue, secondvalue, p1, p2);
// value pointed by p2 = value pointed by p1
*p2 = *p1;
print("After settings *p2 to *p1", firstvalue, secondvalue, p1, p2);
// p1 = p2 (value of pointer is copied)
p1 = p2;
print("After pointing p1 to p2", firstvalue, secondvalue, p1, p2);
// value pointed by p1 = 20
*p1 = 20;
print("After setting *p1 to 20", firstvalue, secondvalue, p1, p2);
return 0;
}
On my system, this produces:
Initial values:
first value is 5
second value is 15
first pointer is at 0x7fffe8171510 with value 5
second pointer is at 0x7fffe8171514 with value 15
After setting *p1 to 10:
first value is 10
second value is 15
first pointer is at 0x7fffe8171510 with value 10
second pointer is at 0x7fffe8171514 with value 15
After settings *p2 to *p1:
first value is 10
second value is 10
first pointer is at 0x7fffe8171510 with value 10
second pointer is at 0x7fffe8171514 with value 10
After pointing p1 to p2:
first value is 10
second value is 10
first pointer is at 0x7fffe8171514 with value 10
second pointer is at 0x7fffe8171514 with value 10
After setting *p1 to 20:
first value is 10
second value is 20
first pointer is at 0x7fffe8171514 with value 20
second pointer is at 0x7fffe8171514 with value 20
As you can see, after that line the two pointers point at the same location, and dereferencing them yields the same value.
Edited by rip-off, 05 December 2012 - 05:07 AM.