user20844 user20844 - 1 year ago 107
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]


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

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

int ary[sizeY][sizeX]


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download