Initializing Pointers with Address-Of Operator (&)
int number = 88; // An int variable with a value
int * pNumber; // Declare a pointer variable called pNumber pointing to an int (or int pointer)
pNumber = &number; // Assign the address of the variable number to pointer pNumber
int * pAnother = &number; // Declare another int pointer and init to address of the variable number
Indirection or Dereferencing Operator (*)
int number = 88;
int * pNumber = &number; // Declare and assign the address of variable number to pointer pNumber (0x22ccec)
cout << pNumber<< endl; // Print the content of the pointer variable, which contain an address (0x22ccec)
cout << *pNumber << endl; // Print the value "pointed to" by the pointer, which is an int (88)
*pNumber = 99; // Assign a value to where the pointer is pointed to, NOT to the pointer variable
cout << *pNumber << endl; // Print the new value "pointed to" by the pointer (99)
cout << number << endl; // The value of variable number changes as well (99)
The reason why the value of number has been changed to 99 is because:
- pointer
pNumber
has been assign the address ofnumber
- then
pNumber
has been assign the value 99 - thus the value 99 will go into the content of address of number
https://www.ntu.edu.sg/home/ehchua/programming/cpp/cp4_PointerReference.html