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] 


4/1/2016 12:15:41 PM

Accepted Answer

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

2/15/2018 10:33:16 PM

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

should be:

int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
    ary[i] = new int[sizeX];

and then clean up would be:

for(int i = 0; i < sizeY; ++i) {
    delete [] ary[i];
delete [] ary;

EDIT: as Dietrich Epp pointed out in the comments this is not exactly a light weight solution. An alternative approach would be to use one large block of memory:

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

// ary[i][j] is then rewritten as

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow