How do i allocate memory for a 2d array?

Nirvan picture Nirvan · Apr 8, 2012 · Viewed 21.7k times · Source

How do i declare a 2d array using the 'new' operator? My book says this:

int (*p)[4];
p=new[3][4];

but it doesn't make sense to me. p is a pointer to an array of 4 ints, so how can it be made to point to a 2d array?

Answer

Miroslav Mares picture Miroslav Mares · Apr 8, 2012

It seems you need pointer to pointer. EDIT: Well, to be more exact, the following example creates an array of pointers to arrays.

First do:

int **p = new int*[NUM];

Here you've created array of pointers. Now you need to create another array for every of them. That you can do this way:

for(int i = 0; i < NUM; i++)
{
    p[i] = new int[ANOTHER_NUM];
}

For deallocation you do similar, but in reverse way:

for(int i = 0; i < NUM; i++)
{
    delete[] p[i];
}

And finally:

delete[] p;

Now you can work with it. This way you can create N-dimensional array, just add more '*'. If you have any other particular question, ask in the comments, please.

But, generally, for further info I recommend you to try Google first with questions like "2D array in C++" or "dynamic allocation of 2D array C++", i. e. this query.