How to Initialize a Dynamic Array in C++?
Last Updated :
31 Jan, 2024
In C++, dynamic arrays allow users to allocate memory dynamically. They are useful when the size of the array is not known at compile time. In this article, we will look at how to initialize a dynamic array in C++.
Initializing Dynamic Arrays in C++
The dynamic arrays can be initialized at the time of their declaration by using list initialization as shown:
data_type* pointer_variableName = new data_type[ array_size] {element1, element2, ...} ;
C++ Program to Initialize Dynamic Arrays
C++
#include <iostream>
using namespace std;
int main()
{
int size = 5;
int * arr = new int [size]{ 1, 2, 3, 4, 5 };
cout << "Elements of the array are: " << endl;
for ( int i = 0; i < size; i++) {
cout << arr[i] << " " ;
}
delete [] arr;
return 0;
}
|
Output
Elements of the array are:
1 2 3 4 5
Note: If we create a dynamic array without specifying initial values, the elements will not be initialized, and their values will be undefined.
Share your thoughts in the comments
Please Login to comment...