×

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

Passing by Reference Vs. Passing by the pointer in C++

 Passing by Reference Vs. Passing by the pointer in C++ Throughout C++, it can transfer parameter values except by pointers or through referring to a function. For both cases, we have...

3 minutes read.

Structure Vs Class in C++

The structure in C++ is similar to that of a class, with a few exceptions. Both the structure and the stage, the most important thing is safety. The property is...

4 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.

Malloc() and new in C++

In C ++, malloc () and new are used for the same thing. During runtime, they are used to allocate memory. Malloc () and the new, on the other hand,...

4 minutes read.

Constructor Vs Destructor in C++

C++ Constructor A function Object () { [native code] } is a member function that shares the same name as the class. It is called automatically whenever a class object is...

3 minutes read.

C++ Break

In this article, we will discuss the C++ Break statement with its syntax, algorithm, pseudocode, and examples. The C++ break statement also terminates the currently active loop or switch statement immediately....

4 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Hybrid Inheritance

C++ Hybrid Inheritance When more than one type of inheritance is combined in single inheritance is called as hybrid inheritance. C++ Hybrid Inheritance Example #include<iostream>   using namespace std;   class Student{       protected:           int rollno;       public:           void getRoll(int a){               rollno=a;           }           void putRoll(void){               cout <<"Roll No: "<< rollno<<endl;           }   };   class Test : public Student{       protected:           float subject1, subject2;       public:           void getMarks(float x, float y){               subject1=x;               subject2=y;           }           void putMarks(void){               cout<< "Marks gain: "<<endl <<"Subject1 =  "<<subject1<<endl<<"Subject2 = "<<subject2 <<endl;           }   };   class Sport{       protected:           float score;       public:           void getScore(float s){               score=s;           }           void putScore(void){               cout<<"Sports score: "<<score<<endl;           }   };   class Result : public Test, public Sport{       float total;       public:           void display(void);   };   void Result:: display(void){       total=subject1+subject2+score;       putRoll();       putMarks();       putScore();       cout<<"Total Score: "<<total<<endl;   }   int main(){       Result stu;       stu.getRoll(10);       stu.getMarks(40,50);       stu.getScore(60);       stu.display();       return 0;   } Output: Roll No: 10 Marks gain: Subject1 = 40 Subject2 = 50 Sports score: 60 Total...

1 minute 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.

C++ Program For FCFS (First Come First Serve)

The most basic scheduling technique is FCFS, often known as "FIFO (First In, First Out)". In this procedure, the first one is utilized and executed first, while the second one...

4 minutes read.

The Stock Span Problem

It is necessary to determine the span of a stock's price throughout all n days in order to solve the stock span problem, which involves a set of n daily...

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.

Skyline Problem in C++

We have given n rectangular buildings in a 2-dimensional city. Here, to compute the Skyline of the given n rectangle structures in a two-dimensional metropolis while removing hidden lines, the...

3 minutes read.

Hexadecimal to Decimal in C++

In computers, hexadecimal numbers are represented with base 16 and decimal numbers are represented with base 10 and values 0-9, whereas hexadecimal numbers have digits ranging from 0 to 15,...

3 minutes read.

Factorial Program in C++

C++ Factorial Program: The product of all positive descending integers is the factorial of n. n! denotes the factorial of n. For instance: 5! = 5*4*3*2*1=120 4! = 4*3*2*1=24 In Combinations and Permutations, the...

4 minutes read.

C++ array to function

Arrays in C++ : Instead of defining distinct variables for each item, arrays are used to hold numerous values in a single variable. An array can be declared by specifying the variable...

4 minutes read.

Bitmasking in C++

Bitmasking is a technique that is used to access a particular bit within the data bytes. When you apply the iterative approach, this phenomenon is used. A bitmask is described...

6 minutes read.

C++ Object Class

C++ Object Class Overview: C++ is a high-level programming language and an object-oriented programming language. An object-oriented language always has some properties of classes and objects. In this article, we...

4 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.