Open In App

How to Initialize a Dynamic Array in C++?

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++ program to demonstrates the initialization of a
// dynamic array using a new keyword.
  
#include <iostream>
using namespace std;
  
int main()
{
  
    int size = 5;
    // initializing a dynamic array
    int* arr = new int[size]{ 1, 2, 3, 4, 5 };
  
    // printing the array elements
    cout << "Elements of the array are:  " << endl;
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
  
    // freeing-up memory space by deleting arr
    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.



Article Tags :