Source of pointers6.cpp


  1: //pointers6.cpp

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

  6: int main()
  7: {
  8:     cout << "\nThis program illustrates dynamic memory deallocation.";
  9:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 11:     cout << "\nFirst we declare a dynamic variable, fill it with a "
 12:         "value, and display that\nvalue. Then we return the variable "
 13:         "storage to the heap and try once again to\ndisplay the value.\n";

 15:     int* p_int1 = new int;
 16:     *p_int1 = 17;
 17:     cout << *p_int1 << endl;

 19:     delete p_int1;
 20:     cout << *p_int1 << endl;
 21:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');


 24:     cout << "\nNow we declare a dynamic array, fill it with values, "
 25:         "display the values, then\nreturn the array storage to the "
 26:         "heap and try once again to display the values.\n";

 28:     int* p_int2 = new int[5];
 29:     for (int i = 0; i < 5; i++) p_int2[i] = i + 1;
 30:     for (int i = 0; i < 5; i++) cout << p_int2[i] << " ";  cout << endl;

 32:     delete [] p_int2;
 33:     for (int i = 0; i < 5; i++) cout << p_int2[i] << " ";  cout << endl;
 34:     cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 35: }