### Thread: C++ Memory Allocation Problem

1. No Profile Picture
Junior Member
Devshed Newbie (0 - 499 posts)

Join Date
Aug 2003
Posts
3
Rep Power
0

#### C++ Memory Allocation Problem

How can i declare a 2D int array dynamically?
Thx :(
2. No Profile Picture
Contributing User
Devshed Beginner (1000 - 1499 posts)

Join Date
Feb 2001
Posts
1,481
Rep Power
15
METHOD 1:

int my_array[4][2];

The type of an array does not include the leftmost dimension, so the type of my_array is:

int[ ] [2]

The syntax for a pointer to that type is:

int (*parray)[2]

So, to dynamically allocate memory using new for my_array, you would do this:

int (*parray)[2] = new int[4][2];

METHOD 2:
Another syntax for declaring a pointer to a two dimensional array is this:

int ** Arr2D;

(a pointer to an array of pointers)

To dyanamically allocate memory for that array involves two steps: 1) getting an address for an array of pointers, and 2) getting an address for a one dimensional array for each pointer:

int** Arr2D;
Arr2D = new int*[3];

That would create an array of 3 int pointers. Since an int pointer can point to a one dimensional array of int's, you can use each of the int pointers to store the address of a single dimensional array like this:

Arr2D[0]=new int[10];
Arr2D[1]=new int[10];
Arr2D[2]=new int[10];

To delete Arr2d, you need to first delete each one dimensional pointer you allocated memory for:
Code:
```for(int i=0; i<3; i++)
{
delete [ ]  Arr2d[i];
}```
Then you need to delete the memory you allocated for the array of pointers:

delete [ ] Arr2d;
Last edited by 7stud; August 25th, 2003 at 04:51 AM.