user20844 user20844 - 18 days ago 8
C++ Question

How do I declare a 2d array in C++ using new?

How do i declare a 2d array using new?

Like, for a "normal" array I would:

int* ary = new int[Size]


but

int** ary = new int[sizeY][sizeX]


a) doesn't work/compile and b) doesn't accomplish what:

int ary[sizeY][sizeX]


does.

Answer

A dynamic 2D array is basically an array of pointers to arrays. You should initialize it using a loop, like this:

int** ary = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
    ary[i] = new int[colCount];

The above, for colCount= 5 and rowCount = 4, would produce the following:

enter image description here