Dynamic Allocation of Arrays in C++
In C++, we use the new operator for dynamic memory allocation . To allocate an array dynamically,
- Start by declaring a pointer that will store the base address of the allocated array.
- Next, use the new operator to reserve memory space to accommodate an array of a particular data type.
- When making this allocation specify the size of the array that indicates how many elements it can contain. This specified size determines the amount of memory to be allocated.
Syntax to Dynamically Allocate Arrays
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.
C++ Program to Dynamically Allocate an Array
The below program demonstrates the dynamic array allocation in C++.
// C++ program to demonstrate how to dynamically allocate
// array
#include <iostream>
using namespace std;
int main()
{
// Take array size as input from user
cout << "Enter the size of the array: ";
int size;
cin >> size;
// Dynamically allocate an array
int* arr = new int[size];
// Assign values to the array elements
for (int i = 0; i < size; i++) {
arr[i] = i + 1;
}
// Print the array elements
cout << "Elements of the array are: ";
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
// Deallocate the memory
delete[] arr;
return 0;
}
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
delete[]
operator after use to prevent memory leaks.
How to Dynamically Allocate an Array in C++?
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++.
Contact Us