×

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

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Array of Vectors in C++ STL

Prerequisites: C++ STL Arrays and C++ STL Vector. A group of items kept in consecutive memory region is known as an array. It is to group similar objects of the same...

4 minutes read.

Method overriding in C++

What is method overriding? Using the same function in derived class as their base class is referred to as function/method overriding in c++. Method overriding is an example of polymorphism. With...

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

Substring in C++

A substring is a function in c++ that is imported from the string library. An element of a string is called a substring. A substring contains two parameters length and...

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

User-defined literals in C++

Introduction to User-Defined Literals: User-defined literals, introduced in C++11, are a way to extend the C++ language to allow users to define their literal suffixes and the corresponding behavior. These suffixes...

7 minutes read.

RTTI (Run-Time Type Information) in C++

In C++, RTTI or Run-Time Type Information reveals information about the data type of an object at runtime and only works with classes that have at least one virtual function....

3 minutes read.

rand() and srand() in C / C++

In this tutorial, we'll explore the syntax, usage, and examples of the C++ STL functions rand() and srand(). What exactly is rand()? The C++ STL's built-in rand() function is defined in the...

3 minutes read.

Unary Operators in C++

Unary operators in C++ Unary operator: is operations that function to produce a new value on a single operand. a) unary minus: A minus operator modifies the argument's symbol. A positive number...

3 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

Diamond Pattern Using Do-While loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

5 minutes read.

C++ Nested if

C++'s nested if statements enable more complex decision-making when a section of code needs to execute only after a set of conditions is met. The nested if control statement refers...

4 minutes read.

C++ String Concatenation

C++ String Concatenation In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs. What is the String Concatenation? The + operator...

3 minutes read.

C++ storage classes

Storage Classes are used to characterize a variable's or function's characteristics. These characteristics include scope, visibility, and life-time, which allow us to track the presence of a variable over the...

5 minutes read.

Destructor

Let’s discover the C++ destructor, virtual and pure virtual destructors, and when destructors are invoked and their rules in this lesson. Destructors : A member function that destroys an object is known as...

5 minutes read.

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

Functors in C++

Functors are not a very popular thing among beginner or intermediate-level programmers. But this thing is very useful and helpful. The name functor suggests us some similarities with function. It...

3 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

New Operator in C++

Dynamic memory allocation in C++ means manually allocating the memory by the developer duing run-time. The dynamic memory is allocated in the heap section of the RAM, whereas the static...

3 minutes read.