Nov 3, 2011 at 12:32am Nov 3, 2011 at 12:32am UTC
p1 == p2, as shown by the printout, which means the two pointers have the same address, but why the values are different after *p1=20? When two pointers point to the same location, modification of one value should automatically update the value for the second pointer. Any misunderstanding?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
using namespace std;
int main ()
{
int a = 5, b = 15;
int * p1, * p2;
p1 = &a;
p2 = &b;
*p1 = 10;
*p2 = *p1;
p1 = p2;
*p1 = 20;
cout << "a: " << a << endl;
cout << "b: " << b << endl;
cout<<"p1:" <<p1<<" p2:" <<p2<<endl;
return 0;
}
output:
a: 10
b: 20
p1:0x28ff00 p2:0x28ff00
Last edited on Nov 3, 2011 at 12:33am Nov 3, 2011 at 12:33am UTC
Nov 3, 2011 at 12:35am Nov 3, 2011 at 12:35am UTC
Nevermind, you answered my question. Now I'll answer yours.
a is an int in some sort of memory block.
b is an int in some sort of memory block.
p1 and p2 are pointers that point at the same memory block (at the end of the program).
Both p1 and p2 are pointing at the memory address of b.
a doesn't get changed because neither of the pointers are pointing at it anymore
Last edited on Nov 3, 2011 at 12:39am Nov 3, 2011 at 12:39am UTC