/* Filename: dynamic.cpp Author: Br. David Carlson Date: July 30, 1998 Last Revised: December 1, 2001 This program shows how to dynamically allocate space for a plain integer and for an array of integers, freeing up the space after it is no longer needed. Finally, it shows two ways of using pointers to set up strings. Tested with: Microsoft Visual C++ 6.0 Microsoft Visual C++ .NET g++ under Linux */ #include using namespace std; const int MAX = 16; typedef int * IntPtrType; typedef char * CharPtrType; int main(void) { IntPtrType IntPtr; int NumItems, k; CharPtrType Msg1 = "This is a message"; CharPtrType Msg2; // First, let's dynamically allocate space for an int: IntPtr = new int; if (IntPtr == NULL) { cerr << "Could not allocate sufficient space" << endl; exit(1); } // Then use this int for something: *IntPtr = 55; cout << "The int pointed to by IntPtr is " << *IntPtr << endl << endl; // Deallocate the space used by *IntPtr: delete IntPtr; // Next, let's dynamically allocate an array of ints: cout << "Enter the number of integers you wish to store:" << endl << "(use a small positive integer): "; cin >> NumItems; cout << endl << endl; IntPtr = new int[NumItems]; if (IntPtr == NULL) { cerr << "Could not allocate sufficient space" << endl; exit(1); } // Then use this array: for (k = 0; k < NumItems; k++) { cout << "Enter an integer to store: "; cin >> IntPtr[k]; } cout << endl << "The values stored in the array are:" << endl; for (k = 0; k < NumItems; k++) cout << IntPtr[k] << " "; cout << endl; // Use [] when deleting an array: delete [] IntPtr; // Let's output the first message: cout << endl << Msg1 << endl; // Then let's allocate space and fill in the second message: Msg2 = new char[16]; if (Msg2 == NULL) { cerr << "Could not allocate sufficient space" << endl; exit(1); } strcpy(Msg2, "A new message"); cout << Msg2 << endl; // Delete the space for the message array: delete [] Msg2; return 0; }