Source of TestStuff20141006.cpp


  1: //TestStuff20141006.cpp

  2: //Monday, October 6, 2014

  3: 
  4: #include <iostream>

  5: using namespace std;
  6: 
  7: #include "utilities.h"

  8: using Scobey::Pause;
  9: 
 10: int main(int argc, char* argv[])
 11: {
 12:     int i = 12; //A "regular" variable

 13:     cout << i << endl; //Let's output its value

 14:     cout << &i << endl; //Let's output the memory address where it's stored

 15:                         //Note: & (in this context) is called the

 16:                         //"address of" operator (&i is the "address of i")

 17: 
 18:     int* iPtr = &i; //A pointer variable containing the address of i

 19:     cout << iPtr << endl; //Displays same value as &i

 20:     cout << *iPtr << endl; //iPtr "dereferenced" is another name for i

 21: 
 22:     *iPtr = 15; //Also changes the value in i

 23:     cout << i << endl; //As we can see here

 24:     cout << *iPtr << endl; //Same value that's in i

 25: 
 26:     iPtr = new int; //Now get an "anonymous" storage location from "the heap"

 27:                     //Another name for "the heap" is "the free store"

 28:                     //Java also uses the heap, but more "behind the scenes"

 29:     cout << iPtr << endl;  //Not a value we're interested in

 30:     cout << *iPtr << endl; //Outputs a garbage value

 31:     *iPtr = 25; //Now we've stored a value in our location on the heap

 32:     cout << *iPtr << endl; //Let's confirm that our value 25 is there

 33:     delete iPtr; //Note careully!! iPtr doesn't go anywhere ... what this does

 34:                  //is break the connection between the pointer and the thing

 35:                  //that it points to

 36:     cout << *iPtr << endl; //We no longer have access to 25; garbage again

 37:     iPtr = nullptr; //Good practice: explicitly says that iPtr does not point

 38:                     //at anything

 39: 
 40:     //Make sure you know how to draw "pointer pictures"!!!!

 41:     //The Ptr suffix in iPtr is not necessary, just a convenient convention

 42:     //to help distinguish "pointer variables" from "regular variables".

 43: }
 44: