1: //TestStuff51.cpp 2: //Tuesday, Mar 25, 2014 3: 4: #include <iostream> 5: #include <fstream> 6: #include <string> 7: #include <iomanip> 8: #include <cstdlib> 9: using namespace std; 10: 11: #include "utilities.h" 12: using Scobey::Pause; 13: 14: int main(int argc, char* argv[]) 15: { 16: //int i = 6; 17: //cout << i << endl; 18: //cout << &i << endl; //& is the "address of" operator 19: 20: //int* iPtr; //iPtr is a "pointer variable", point at an int location 21: //iPtr = &i; //iPtr can contain the address of an "ordinary" variable i 22: //cout << iPtr << endl; //Shows same value as &i 23: //cout << *iPtr << endl; //iPtr is "dereferenced" 24: //to give the value at its address 25: 26: //iPtr = new int; //Now iPtr points at a location on "the heap" 27: //cout << *iPtr << endl; //Outputs a garbage value 28: //*iPtr = 15; //Put 15 in that location on the heap 29: //cout << *iPtr << endl; //Confirm that 15 is indeed there 30: 31: //delete iPtr; //Return the storage to the heap if it's no longer needed 32: //cout << *iPtr << endl; //Garbage again 33: //iPtr = nullptr; //Says explicitly that iPtr does not point at anything 34: //cout << *iPtr << endl; //So now we get a program crash 35: 36: //The sizeof operator returns the number of bytes occupied by a type 37: //or a variable of a certain type 38: //int i = 6; 39: //cout << sizeof (i) << endl; 40: //cout << sizeof (int) << endl; 41: //int a[] = {1, 2, 3, 4, 5}; 42: //cout << sizeof (a) << endl; 43: 44: //int a[] = {1, 2, 3, 4, 5}; //An ordinary array of int values 45: //int* iPtr = &a[0]; //iPtr points at the first of those values 46: //cout << *iPtr << endl; //Shows the first value in the array 47: //iPtr = &a[3]; //iPtr points at the 4th value in the array 48: //cout << *iPtr << endl; //Shows the 4th value in the array 49: 50: int a[] = {1, 2, 3, 4, 5}; 51: cout << *a << endl; //OK because the name of an array is also a pointer 52: //to its first element 53: int* iPtr = a; //Equivalent to int* iPtr = &a[0]; 54: cout << *iPtr << endl; //Shows the first element of the array 55: 56: //We can do "pointer arithmetic" if our pointer points into an array. 57: //That is we can increment and decrement such a pointer variable, or 58: //add or subtract an integer to or from the pointer value, and this 59: //arithmetic is "smart" in the sense that the pointer value will move 60: //the required number of bytes (4 for ints, 8 for doubles, for example). 61: iPtr++; 62: cout << *iPtr << endl; 63: cout << *(iPtr + 2) << endl; 64: }