#include <iostream>
using namespace std;
int main()
{
int x;
x = 5;
cout << "x is initially " << x << endl << endl;
int* myptr; // variable myptr can be used to store the memory address of any int variable
myptr = &x; // here the &x looks up the memory address of variable x,
// which we then store in myptr
cout << "after storing the address of x into myptr," << endl;
cout << " the memory address stored in myptr is " << myptr << endl;
cout << "and the value we find in that memory location is " << (*myptr) << endl << endl;
*myptr = 10; // *myptr refers to whatever is stored at the given address,
// i.e. (*myptr) is now a way of indirectly getting at x's contents
cout << "after putting value 10 into memory at that location," << endl;
cout << " x is now " << x << endl << endl;
myptr = nullptr; // nullptr is a special value, an alias for memory address 0,
// which is generally used to indicate that a pointer variable
// currently is NOT actually 'pointing at' anything
cout << "After assigning null as a memory address," << endl;
cout << " myptr is now " << myptr << endl << endl;
cout << "and the value stored at that location is: ";
cout << (*myptr) << endl << endl;
// here ^^^^^^ the program crashes (segmentation fault) because we tried to
// look at the memory contents at address 0, which isn't a valid address
}
x is initially 5
after storing the address of x into myptr,
the memory address stored in myptr is 0x7ffce2a55954
and the value we find in that memory location is 5
after putting value 10 into memory at that location,
x is now 10
After assigning null as a memory address,
myptr is now 0
Segmentation fault
|