Way back early in the tutorials I read the c++ tutorials page on pointers and references which helped me coming into this.
int val1 = 1;
int val2 = 2;
int val3 = 3;
int* valPtr = &val1;
int& valRef = val2;
I’ve changed it up and added another value while also pointing the reference to val2.
So at first in the order of Val1, Val2, Val3, valPtr, valRef my output would be:
(1,2,3,1,2)
The address would be:
(Add_A, Add_B, Add_C, Add_A, Add_B)
Now I can change the value of val3 in 1 of two ways. I could assign the memory address a new value, or I could change the memory address that val3 is stored.
val3 = *valPtr;
The should change val3 to (1, Add_C). It’s kept the same memory address but changed the value within it. testing this returns true.
Now I can change it the other way.
&val3 = valPtr;
this should chane val3 to (1, Add_A). It hasn’t copied the value, it’s changed it’s memory address. Whoops this doesn’t work! Compile error!
However;
valPtr = &val3;
this returns valPtr as (3, Add_C). I have changed the ADDRESS the pointer is referring to, however have left the value in its original address untouched.
So it seems you can assign a value to the value of a pointer. However you cannot assign the address of a value to the address of the pointer.
You can assign the Address of the pointer to the address of the value however. I suppose this makes sense. You can’t just be shifting the value address, what if the address it is moving to already has a value? PROBLEMS!
Now for references let’s try the same thing. Let’s first try and change the value while maintaining the address.
valRef = val3;
this returns valRef as (3, Add_B). Success! we have reassigned the value in memory address Add_B using a reference.
now let’s try to change the ADDRESS valRef is reffering to.
&valRef = &val3;
Compile error “expression must be a modifiable lvalue” So much like the actual value, the reference address cannot be changed >=(
okay lets try break something.
std::string Address = "";
Address = &val3
std:cout << Address;
Oh well too ambitious. Well instead of writing:
*valPtr = val3;
we instead wrote
*valPtr = &val3
we would be storing Add_C into the value of Add_A. Which obviously doesn’t work! that’s why I was trying to store it into a string but c++ can not just convert 012FB048 to a string so easily.