×

How to declare a 2D array dynamically in C++

In this article, we will learn how to declare the dynamic array in C++. We also learn the initialization of a 2D array using a pointer in C++. Here, we will cover the following topics:

  • Details about Dynamic memory allocation.
  • About the new and delete operator in C++.
  • The creation process of the 2D array in C++.

Dynamic memory allocation

Dynamic memory allocation is a process of allocating memory during the run time with the help of a heap. With the help of dynamic memory allocation, the programmer can perform the memory allocation manually.

In C++, we also use the new and delete operator to assign and free the memory allocation process.

New operator

With the help of the new operator, we can request the heap to assign the memory allocation. If sufficient memory space is available, the heap will create a new variable or new object during the run time of the program. It also returns the pointer value to the newly allocated space.

Syntax:  

new data_type;

Syntax for memory allocation:

new data_type[size_of_array];

Delete operator

The dynamically allocated memory needs to be freed as soon as the program is completed. With the help of the delete operator, we can release or deallocate the memory location which is occupied by the variable or the object.

Syntax for deallocation memory of a single object:

delete pointer;

Syntax for deallocation memory of a single object:

delete() pointer;

Dynamically allocate a 2D array in C++

There are some steps to allocate the memory in the 2D array. The steps are as follows: ,

Step-1

First, we need to create the pointer in the pointer variable.

Syntax:  

int** arry;

Step-2

Then we need to allocate the memory allocation with the help of a new operator, and the pointer will store the reference value in the array.

Syntax:  

arry = new int*[row];

Step-3

We can perform the memory allocation of each row in 2D using the loop concept.

Syntax:

for(int i = 0;i < row;i++) {
    arry[i] = new int[col];
}

Step-4

Now, we have to provide the input in the array using the loops.

Syntax:

for(int i = 0;i < row;i++) {
    for(int j = 0;j < col;j++) {
          cin >> arry[i][j];
       }
  }

Step-5

Finally, after allocating the memory, we need to release the variable from the memory location.

Syntax:

for(int i = 0; i < row;i++) {
    delete[] arry[i];
 }

Step-6

After completing the above process, we need to delete the pointer to the array of points.

Syntax:

delete[] arry;

Program to create a 2D array in C++

Example 1:

#include <iostream>
 
using namespace std;
 
int main() {
 
  int ** arry;
  int row, col, i, j;
 
  cout << "Number of Rows:" << endl;
  cin >> row;
  cout << "Number of Columns:" << endl;
  cin >> col;
 
  
  arry = new int * [row];
 
  
  for (i = 0; i < row; i++) {
    arry[i] = new int[col];
  }
 
 
  cout << "Enter " << (row * col) << " numbers to the Array\n";
  for (i = 0; i < row; i++) {
    for (j = 0; j < col; j++) {
      cout << "Enter the elements at Row " << i + 1 << " Column " << j + 1 << endl;
      cin >> arry[i][j];
    }
  }
 
  
  cout << "Here is your 2D Array:" << endl;
  for (i = 0; i < row; i++) {
    for (j = 0; j < col; j++) {
      cout << arry[i][j] << ' ';
    }
    cout << endl;
  }
 
 
  for (i = 0; i < row; i++) {
    delete[] arry[i];
  }
 
  delete[] arry;
 
  return 0;
}
 

Output:

Number of Rows:
3
Number of Columns:
3
Enter 9 numbers to the Array
Enter the elements at Row 1 Column 1
1
Enter the elements at Row 1 Column 2
2
Enter the elements at Row 1 Column 3
3
Enter the elements at Row 2 Column 1
4
Enter the elements at Row 2 Column 2
5
Enter the elements at Row 2 Column 3
6
Enter the elements at Row 3 Column 1
7
Enter the elements at Row 3 Column 2
8
Enter the elements at Row 3 Column 3
9
Here is your 2D Array:
1 2 3 
4 5 6 
7 8 9

Example 2:

#include <iostream>
using namespace std;
int main()
{


               int m = 3, n = 4, c = 0;


               
               int* arr = new int[m * n];


               
               for (int i = 0; i < m; i++) {
                               for (int j = 0; j < n; j++) {
                                               *(arr + i * n + j) = ++c;
                               }
               }
               for (int i = 0; i < m; i++) {
                               for (int j = 0; j < n; j++) {
                                               cout << *(arr + i * n + j)
                                                               << " ";
                               }
                               cout << endl;
               }
               delete[] arr;


               return 0;
}

Output:

1 2 3 4 
5 6 7 8 
9 10 11 12

Related Topics

Message Passing in C++

The act of sending and receiving information by an object is referred to as communication, and all communication between objects that takes place via message is known as message passing....

1 minute read.

Compile Time Polymorphism in C++

What is Polymorphism? Polymorphism refers to the existence of various forms. Polymorphism can be simply defined as a message's capacity to be presented in multiple forms. One application of polymorphism in...

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

How to Use Getline in C++

What is getline in C++? Similar to the cin function, which allows the programmer to take input from the user getline() function also takes input from the user. But in this...

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.

System() function in C++

As a part of the c/c+ standard library, the system() function passes commands to be executed by the operating system’s command processor or terminal and returns the completed command. We...

2 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

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

Virtual Function Vs Pure Virtual Function

Virtual activity is a member function defined in the foundation phase that can be redefined by acquired classes. Let's have a look at an example: #include <iostream>   #include <bits/stdc++.h> #include <stdlib> using namespace std;   class Base   {    ...

5 minutes read.

Virtual base class in C++

Consider in a C++ program, there are 4 classes named class A, class B, class C, and class D. If class B and class c inherit properties from class A....

3 minutes read.

C++ For loop

C++ loop Statement C++ Loop statement allows us to repeat the execution of a statement or group of statements multiple times. The statement(s) repeat execution within loop until the condition of loop...

2 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

C++ Bitwise XOR Operator

Exclusive OR is another name for the bitwise XOR operator. The ‘^’ is used to indicate it. It operates at the bit level of the operands, as the name implies....

4 minutes read.

Splitting a string in C++

Any programming language must have the ability to work with string data. For programming needs, we sometimes need to separate string data. Many computer languages provide a split() method that...

4 minutes read.

C++ Memory Management

Memory management is a method of controlling computer memory and allocating memory space to applications to increase overall system performance. What is the purpose of memory management? Because the array contains homogeneous...

4 minutes read.

C++ Constructor

Constructor is a specific method in C ++ that is automatically called when an object is created. Typically, it is used to set the data members of a new object....

4 minutes read.

C++ Date and Time

The date and time formats in C++ will be covered in this article. Because C++ lacks a proper date and time format, we must rely on the c language. The...

7 minutes read.

Maps in C++

Maps: Maps in C++ are the containers associated with key and mapped values. By keys and mapped values, we mean that the maps are used to store elements formed by the...

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

Array of sets in C++

Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. A collection of data objects stored in a continuous way is...

6 minutes read.