# Thread: multidimensional array and malloc

1. ## multidimensional array and malloc

Im trying to use malloc to allocate memory for a multi dimensional array of ints. After this code has finished i want to be able to address it with plane[x][y]. Does any one know what i'm doing wrong here?

Code:
```
// Declare variables
int plane_width = 10, plane_height = 10, x, y;
int * plane;

// Allocate memory for first dimension of  plane
if ( ( ( plane = malloc( sizeof( int * ) * plane_width ) ) == NULL ) ) {
fprintf( stderr, "No memory available\n" );
exit( EXIT_FAILURE );
}
// Allocate memory for second dimension of plane
for ( x = 0; x < plane_width; x++ ) {
if ( ( ( plane[x] = ( int * ) malloc( sizeof( int ) * plane_height ) ) == NULL ) ) {
fprintf( stderr, "No memory available\n" );
exit( EXIT_FAILURE );
}
// Set tile to default value
for ( y = 0; y < plane_height; y++ ) {
plane[x][y] = TILE_UNINITIALISED;
}
}```

int **plane;

Lose the malloc casts - they're hiding your real problem.

The general form is T = malloc ( sizeof(*T) * num ), so in your case
plane = malloc( sizeof( *plane ) * plane_width )
plane[x] = malloc( sizeof( *plane[x] ) * plane_height )

3. thanx heaps salem!

4. Just on a side note, there's another way of doing the same thing:

There's been a few times when I've used a library which required the use of the flat[x+w*y] form but where I've wanted the convenience of using two indices like arr2d[y][x].

Code:
```int * flat;
int ** arr2d;
unsigned int i;

flat=malloc(sizeof *flat * w * h);
if (!flat) {
/* handle the error */
}

arr2d=malloc(sizeof *arr2d * h);
if (!arr2d) {
/* handle the error */
}

for (i=0;i<h;i++) {
arr2d[i]=flat+i*w;
}```
You can index the flat array using:

flat[x+w*y]

but also can use:

arr2d[y][x]

to refer to the same element. (Note that the dimensions are reversed.)

Ian Woods

5. And if you make the array dimensions a power of 2, then you can access the linear array as a 2D array by using a simple shift.