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

C++Server Side ProgrammingProgramming

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.


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.

Published on 28-Feb-2018 12:01:32