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++ 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.