Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
August 25th, 2003, 04:27 AM
 ayumi
Junior Member

Join Date: Aug 2003
Posts: 3
Time spent in forums: < 1 sec
Reputation Power: 0
C++ Memory Allocation Problem

How can i declare a 2D int array dynamically?
Thx

#2
August 25th, 2003, 04:48 AM
 7stud
Contributing User

Join Date: Feb 2001
Posts: 1,365
Time spent in forums: 18 h 20 m 28 sec
Reputation Power: 14
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.

 Viewing: Dev Shed Forums > Programming Languages > C Programming > C++ Memory Allocation Problem