Heap-Allocated Arrays

Heap-allocated arrays are stored on the heap, a region of memory separate from the stack. Memory for heap-allocated arrays is manually allocated and deallocated using functions like new and delete operators.

Syntax

data_type* array_name = new data_type[array_size]

Example

The below example demonstrates how the array is allocated on the heap using the new operator. Memory allocated on the heap persists until it is explicitly deallocated using delete[] keyword.

C++
// C++ Program for Heap-Allocated Arrays

#include <iostream>
using namespace std;

int main()
{

    // Initializing a heap-allocated array
    int* heapArray = new int[5]{ 1, 2, 3, 4, 5 };

    // Printing the elements of heap allocated array
    cout << "Heap-allocated array elements: ";
    for (int i = 0; i < 5; ++i) {
        cout << heapArray[i] << " ";
    }
    cout << endl;
    // Deallocate memory allocated on the heap
    delete[] heapArray;
    return 0;
}

Output
Heap-allocated array elements: 1 2 3 4 5 

Difference Between Stack-Allocated and Heap-Allocated Arrays

In C/C++, arrays can be allocated in two areas of memory: the stack and the heap. Each has its own characteristics and use cases. In this article, we will see the key differences between stack-allocated and heap-allocated arrays.

Similar Reads

Stack-Allocated Arrays

The arrays declared as static arrays in the function or program are called stack-allocated arrays. These arrays are stored on the program’s call stack and the memory for stack-allocated arrays is allocated and deallocated automatically as the program enters and exits the scope where the array is declared. Stack-allocated arrays have a limited lifetime tied to the scope in which they are declared and cannot change its size once they are declared. Once the program exits the scope, the memory allocated for stack-allocated arrays is automatically reclaimed....

Heap-Allocated Arrays

Heap-allocated arrays are stored on the heap, a region of memory separate from the stack. Memory for heap-allocated arrays is manually allocated and deallocated using functions like new and delete operators....

Difference Between Stack-Allocated and Heap-Allocated Arrays

The following table illustrates the key differences between stack-allocated and heap-allocated arrays....