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.
Syntax
DataType array_name[array_size]
Example
The below example demonstrates how the array is allocated on the stack within the function’s scope and once the function returns, the memory allocated for the array is automatically deallocated.
// C++ Program for stack allocated array
#include <iostream>
using namespace std;
int main()
{
// Initializing a stack-allocated array
int stackArray[5] = { 1, 2, 3, 4, 5 };
// Printing the elements of the stack
cout << "Stack-allocated array elements: ";
for (int i = 0; i < 5; ++i) {
cout << stackArray[i] << " ";
}
return 0;
}
Output
Stack-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.