Description:

In this C++ example, we demonstrate how to dynamically allocate and deallocate a single data element and an entire array of elements. Many times we cannot tell whether we need to allocate memory for a variable or how much we need to allocate for an array until runtime. When we need wait until runtime to allocate memory, dynamic allocation and deallocation with new and delete is the solution. In the code below, we demonstrate how to allocate and deallocate a single int and an array of ints.

Example

#include <iostream>

int main()
{
    using namespace std;

    // Allocate a single int and assign it the value 2
    int* ipMyInt        = new int(2);
    // Allocate an array of 6 ints
    int* ipMyIntArray   = new int[6];
    // Fill the array with random values between 0 and 9
    for (int i = 0; i < 6; ++i) {
        ipMyIntArray[i] = (rand() % 10);
    }

    // Output the int and the array
    cout << "Allocated int = " << *ipMyInt << endl;
    cout << "Allocated array = ";
    for (int i = 0; i < 6; ++i) {
        cout << "[ " << ipMyIntArray[i] << " ]";
    }
    cout << endl;

    // Deallocate int
    delete ipMyInt;
    // Deallocate array
    delete [] ipMyIntArray;

    return 0;
}

Output:

Dynamic Allocation Output