So recently I have been learning in combination of this websites tutorials and a Sams C++ book I have found. Anyway onto the subject at hand. When I run the fallowing code it works just fine but I'm confused why firstValue equals 10 when it was assigned the value of 20 where as secondvalue is 20 when I think it should be ten. Specifically what is going on in line 14. Thanks to any one who could explain what's going on here.
Cheers.
Variables contain data... for example an int contains a number.
Pointers are the same, only they contain an address to another variable. When a pointer contains an address of another variable, it is said to "point to" that variable.
When you do *pointer you are not accessing or modifying the pointer... you are instead modifying the variable it points to.
int firstValue = 5, secondValue = 15;
int* p1, * p2;
p1 = &firstValue;
p2 = &secondValue;
// at this point:
// firstValue = 5
// secondValue = 15
// p1 = &firstValue (it "points to firstValue")
// p2 = &secondValue
*p1 = 10; // <- since p1 points to firstValue, this modifies firstValue
// at this point:
// firstValue = 10
// secondValue = 15
// p1 = &firstValue
// p2 = &secondValue
*p2 = *p1; // <- again, not modifying the pointers, but rather the variables they
// point to. So here, we are saying whatever p2 points to (secondValue)
// = whatever p1 points to (firstValue). So basically...
// secondValue = firstValue
// at this point:
// firstValue = 10
// secondValue = 10
// p1 = &firstValue
// p2 = &secondValue
p1 = p2; // <- here.. we ARE accessing the pointers... and not the data they point to
// this effectively makes p1 and p2 point to the same thing
// at this point:
// firstValue = 10
// secondValue = 10
// p1 = &secondValue
// p2 = &secondValue
*p1 = 20; // <- p1 now points to secondValue, so this will modify secondValue
// at this point:
// firstValue = 10
// secondValue = 20
// p1 = &secondValue
// p2 = &secondValue
std::cout << "firstValue is " << firstValue << std::endl; // <- prints 10
std::cout << "secondValue is " << secondValue << std::endl; // <- prints 20