![]() |
VOOZH | about |
In C++, dynamic memory allocation allows us to allocate memory during runtime. Dynamic allocation in an array is particularly useful when the size of an array is not known at compile time and needs to be specified during runtime. In this article, we will learn how to dynamically allocate an array in C++.
In C++, we use the for . To allocate an dynamically,
Below is the general syntax for dynamically allocating an array in C++.
data_type* pointer_variableName = new data_type[array_size];Here,
data_type is the type of data that we want to store in the array. * pointer_variableName declares a pointer variable. new is a keyword used for dynamic memory allocation.array_size is the size of the array we want to allocate. The below program demonstrates the dynamic array allocation in C++.
Output
Enter the size of the array: 5
Elements of the array are: 1 2 3 4 5 Time Complexity: O(1)
Auxilliary Space: O(n), where n is the size of the dynamically allocated array.
Note: Always remember to deallocate the memory using the after use to prevent memory leaks.