×

How to initialize a dynamic array in C++

Regular arrays or static arrays have a predetermined size or fixed size. Change in the size of regular arrays is not possible.

The memory size for static arrays determines at compile time. Dynamic arrays are different from static arrays. The scope for these arrays determines at runtime. The "new" keyword is used to declare the dynamic arrays.

Before understanding the concept of initializing a dynamic array, one must know about the array and dynamic array.

What is an array in C++?

In C++, a collection of data elements of the same data type set in a contiguous memory location is referred to as an array. These data elements are accessed through an index value.

Syntax

datatype array_name[n]= { data_element_1, .. ,data_element_n};

Example

#include <iostream>
using namespace std;
int main()
 {                                         
    int a[4] = { 1, 2, 3, 4};   //array name “a”
    cout<<a[1];                //Compiler creates an array with size 4
    return 0;
 }

Output:

2          

What is a Dynamic Array(C++)?

In C++, a dynamic array is an array in which the size of an array can be changed or modified. It is similar to a static array(regular array), But the array size alters during run time

The memory of a static array is predetermined at the time of array creation, whereas the memory of a dynamic array grows when the array size increments.

The new keyword in C++

A dynamic array is created using the new keyword, and the number of elements to be assigned is defined within the square brackets ([ ]). The datatype is also mentioned.

Syntax

pointer_variable = new data_type[ ];

The mentioned datatype should be a valid datatype of C++.

We can also delete a dynamic array after its creation.

Example 1 (initializing a dynamic array)

#include<iostream>
using namespace std;
int main() {
   int k,p;
   cout<<"Enter total number of data elements:"<<"\n";
   cin>>p;
   int *arr = new int(p);
   cout<<"Enter "<<p<<" data elements"<<endl;
   for(k = 0;k<p;k++) {
      cin>>arr[k];
   }
   cout<<"Entered data elements are: ";
   for(k = 0;k<p;k++) {
      cout<<arr[k]<<" ";
   }
   cout<<endl;
   delete (arr);
   return 0;
}

Output

Enter total number of data elements:
3                                                                                                              
Enter 3 data elements
1                                                                                                             
2
3
Entered data elements are: 1 2 3

In the above program, int *arr = new int(p) is used to initialize the array “arr”. By using delete(arr), memory is retrieved.

Explanation:

The iostream header file is included in the program to use all its functions; the std namespace is used for its classes without calling it. The main() function has the body of the function. Integer variables k and p are used. Integer "p" is used to know the user input for the number of elements, whereas k is used for iteration. Declaring a dynamic array of name "arr", the array "arr" holds the "p" number of integer elements. "int *arr = new int(p)” is used to declare the dynamic array by using the “new” keyword. Use for loop to iterate the array elements mentioned by the user. The program prints desired array of elements. The “endl" is a C++ keyword that means the end of the line. 

Here, the user takes p=3, and the three elements are {1,2,3}.

Example Program 2 (initializing a dynamic array):

In this program, the dynamic array is initialized to zero.

Syntax:

int *arr{ new int[length of the array]{} };

Here, the “length of the array” denotes the number of data elements of the array.

Program

#include<iostream>
using namespace std;
int main() {
   int k,p;
   cout<<"Enter total number of data elements:"<<"\n";
   cin>>p;
int *arr{ new int[p]{} };
  
   cout<<"Entered data elements are: ";
   for(k = 0;k<p;k++) {
      cout<<arr[k]<<" ";
   }
   cout<<endl;
   delete (arr);
   return 0;
}

Output

Enter total number of data elements:
5
Entered data elements are: 0 0 0 0 0

Explanation

The iostream header file is included in the program to use all its functions; the std namespace is used for its classes without calling it. The main() function has the body of the function. Integer variables k and p are used. Integer "p" is used to know the user input for the number of elements, whereas k is used for iteration. Declaring a dynamic array of name “arr”, the array “arr” holds the “p” number of integer elements. “int *arr{ new int[p]{} }”  is used to declare the dynamic array by using “new” keyword with 0 as the initial value. Use for loop to iterate the array elements mentioned by the user. The program prints desired array of elements. The “endl” is a C++ keyword that means the end of the line.  Here, user takes p=5 and the five elements are {0,0,0,0,0}.


Related Topics

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Default Constructor

C++ Default Constructor A default constructor is such constructor which does not take any parameter. A constructor initializes the data member when a class object created. If a programmer does not create any...

2 minutes read.

Assertions in C/C++

Assertions are the statements used to check presumptions which is made by the programmers. Example: Assertion is used to verify whether the malloc returned by the pointer is NULL or not. For...

4 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

C++ History

C++ is a middle-level programming language developed in 1980s by Bjarne Stroustrup at Bel Labs. C ++ development initially started in 1979, four years before its launch. It is started with...

1 minute read.

Array program in C++

What is an Array? An array is a set of identically typed elements that are organized into contiguous memory locations and each element can be independently accessed using an index. We can...

16 minutes read.

Difference between Exit and Return

Define Exit() At the point when a client needs to leave a program from this capability is utilized. A void return type capability calls all capabilities enrolled at the exit and ends...

3 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ Dijkstra Algorithm Using the Priority Queue

In this article we will be finding the shortest routes from a source vertex in a graph to all vertices in the graph, given a graph and a source vertex...

5 minutes read.

C++ Goto

In this article, we will discuss the C++ goto statement with its syntax, use, key features, key points, pseudo code, and examples. What is the goto statement in C++? In C++, the...

4 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

Features and Use of Pointers in C/C++

What is a pointer? A pointer is mainly used to store the address of another variable. The * operator creates a pointer variable, which points to a data type (like an...

7 minutes read.

C++ Program to find largest subarray with 0 sum

Write a program to find the largest subarray that has a sum zero. The array contains positive and negative numbers. Print the length of the max subarray whose sum turns...

4 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples. Ternary Operator: The if-else statement and the conditional operator use...

3 minutes read.

Private Inheritance in C++

Private inheritance is an inheritance in object-oriented programming (OOP) languages where a subclass derives from a superclass. Still, the derived class does not inherit the public and protected members of...

7 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.