please help me with this code
// more pointers
#include <iostream>
usingnamespace std;
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;
}
i can not understand why firstvalue = 10 not 20 ???
*p1 (and similar syntax, p1[0]) IS firstvalue. If you change firstvalue, you changed *p1, and if you change *p1, you change firstvalue. The pointer (p1) is using the exact same memory location because you told it to (p1 = &firstvalue). so if you modify that memory location, you change the value, no matter how you get that value back out (by its firstvalue name or by going to the memory location directly via a pointer, its still the same data).
changing p1 itself is NOT the same thing:
*p1 = 3; //firstvalue is changed.
p1 = 0; //firstvalue did NOT change. This is the pointer. it NO LONGER points to first value if you do this (and will crash, actually, due to trying to access memory that you should not).