Source of pointers5.cpp


  1: //pointers5.cpp

  3: #include <iostream>
  4: using namespace std;

  6: int main()
  7: {
  8:     cout << "\nThis program illustrates the use of pointers with "
  9:         "dynamic arrays,\nwhich essentially parallels their use with "
 10:         "static arrays.";
 11:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 13:     cout << "\nFirst we declare a dynamic array, then we put some values "
 14:         "in it.\nNext we display those values. Finally, we display the "
 15:         "3rd element\nof the array directly, in two different ways.\n";
 16:     int* p_int = new int[5];
 17:     for (int i = 0; i < 5; i++) p_int[i] = i + 1;
 18:     for (int i = 0; i < 5; i++) cout << p_int[i] << " ";  cout << endl;
 19:     cout << p_int[2] << endl;
 20:     cout << *(p_int + 2) << endl;

 22:     //Return the storage allocated to a dynamic array to the heap
 23:     delete [] p_int;
 24:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 25: }

 27: /*
 28:  * Some things to try:
 29:  * What would happen if we tried to display the values this way?
 30:  * Try inserting these three lines after line 20.
 31:     for (int i=0; i<5; i++) cout << *p_int++ << " ";  cout << endl;
 32:     cout << p_int[2] << endl;
 33:     cout << *(p_int+2) << endl;

 35:  * What would happen if we now tried to display the values after deallocation?
 36:  * Try inserting the following line after line 23.
 37:     for (int i=0; i<5; i++) cout << p_int[i] << " ";  cout << endl;
 38:  */