How do I declare a two-dimensional array in C++ using new?


A dynamic 2D array is basically an array of pointers to arrays. So you first need to initialize the array of pointers to pointers and then initialize each 1d array in a loop.

example

#include<iostream>
using namespace std;

int main() {
   int rows = 3, cols = 4;
   int** arr = new int*[rows];
   for(int i = 0; i < rows; ++i)
   arr[i] = new int[cols];
   return 0;
}

This will create an 2D array of size 3x4. Be vary of clearing the memory in such cases as you'll need to delete the memory in the same way you allocated it but in reverse order, ie, you'll need to first delete 1D arrays then the array of pointers.


Updated on: 11-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements