×

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

C++ Fork

A new process known as a "child process" is created with the fork system function and runs concurrently with the process that invoked fork() (parent process). Both processes will carry...

4 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

Include Guards in C++

In C++ programming, we frequently utilize a class more than once, so it is necessary to create a header file and include it in the main program. Now, occasionally a...

3 minutes read.

C++ Convert Int to String

In fact, the conversion of numbers to strings or vice versa represents a significant paradigm change. We often need to convert a number to a string or a string to...

2 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

Leap Year Program in C++

What is a Leap Year? A solar year is the length of time that it takes for Earth to orbit the Sun - approximately 365.25 days. In a calendar year, we...

4 minutes read.

Constructor Overloading

The program contains more than one constructor in a class with the same name, and different types of arguments are called constructor overloading. Calling of constructor depends on the number and types...

2 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

DES in C++

The popularity of the Data Encryption Standard (DES) is slightly declining as a result of the discovery that DES is susceptible to very strong attacks. Since DES is a block cypher,...

3 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

Scope Resolution Operator vs this Pointer in C++

In this tutorial, we will compare the Scope Resolution operation to this Pointer in C++ language. Scope Resolution Operator The Scope Resolution Operator in C++ programming language is usually denoted by (::)....

3 minutes read.

10 Best C and C++ Books for Beginners & Advanced Programmers

If you want to become a skilled software developer, you should never stop learning, whether you're a working professional or a student. Why, therefore, only C or C++? The fundamental...

6 minutes read.

Octal to Decimal in C++

We need to write a system that converts octal number into equal decimal number when octal number is given as input. Let us look at an example of a program in...

2 minutes read.

C++ vardiac() function

In the C++ programming language, the flexibility feature is provided by the variadic function. To understand more about flexibility, let's see the following syntax. Syntax: If we have to add two numbers,...

3 minutes read.

C++ Recursion Function

A programming method called recursion that uses a function to call itself to address lesser problems. The Fibonacci sequence, factorial computation, and tree traversal are just a few of the...

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

LCM Program in C++

What is LCM? LCM is an acronym for "least common multiple". It is used to discover the lowest positive integer divisible by all integers (whose LCM is calculated). For instance, the...

4 minutes read.

C++ Interfaces

The C++ programming language provides programmers with a variety of capabilities and functions. It also enables object-oriented programming, which is essential while working on a project. It will be simple...

7 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.