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

user20844 picture user20844 · Jun 1, 2009 · Viewed 997.4k times · Source

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

Mehrdad Afshari picture Mehrdad Afshari · Jun 1, 2009

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

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

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

enter image description here