1: // Filename: PTR_EX6.CPP
2: // Purpose: Illustrates dynamic storage with both simple and array
3: // variables, as well as "new" and "delete", and the NULL pointer.
5: #include <iostream>
6: #include <cstddef>
7: using namespace std;
9: #include "PAUSE.H"
11: int main()
12: {
13: cout << "\nThis program illustrates dynamic storage "
14: << "with new, delete and NULL."
15: << "\nStudy the source code and the output simultaneously.\n\n";
17: int* iPtr1; // Declare pointer to int.
18: iPtr1 = new int; // Make pointer point to a (dynamic) int location.
19: *iPtr1 = 34; // Put a value (34) in that (dynamic) location.
21: int* iPtr2 = new int; // Declare int pointer/allocate memory at same time.
22: *iPtr2 = 12; // Put a value (12) in that (dynamic) location.
24: // Display the two values.
25: cout << *iPtr1 << " " << *iPtr2 << endl;
26: Pause(0);
28: delete iPtr1; // Return storage pointed to by iPtr1 to free store.
29: iPtr1 = iPtr2; // Make iPtr1 point at storage pointed to by iPtr2.
30: iPtr2 = NULL; // Make iPtr2 point at nothing at all.
31: // Note that at this point we have "lost" 34.
34: // Create a dynamic int array of size 6 pointed to by a.
35: int* a = new int[6];
37: int i;
38: for (i = 0; i < 6; i++) // Put some values in the array.
39: a[i] = i*i*i;
40: for (i = 0; i < 6; i++) // Display the values in the array.
41: cout << a[i] << " ";
42: cout << endl;
43: Pause(0);
45: a[5] = *iPtr1; // Change one of the values in the array.
46: for (i = 0; i < 6; i++) // Display the array values again.
47: cout << a[i] << " ";
48: cout << endl;
49: Pause(0);
51: delete [] a; // Return the array storage to the free store.
53: return 0;
54: }