Horje
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++

// 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.




Reffered: https://www.geeksforgeeks.org


C++

Related
How to Capture std::vector in Lambda Function? How to Capture std::vector in Lambda Function?
How to Redirect cin and cout to Files in C++? How to Redirect cin and cout to Files in C++?
How to use errno in C++? How to use errno in C++?
How to Merge Multiple std::sets into a Single std::set in C++? How to Merge Multiple std::sets into a Single std::set in C++?
How Can I Get All the Unique Keys in a Multimap? How Can I Get All the Unique Keys in a Multimap?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13