# Thread: Run-time error allocating 3-D array

1. ## Run-time error allocating 3-D array

I posted this message earlier in the C forum, and was told this is a C++ problem so I am posting it here. I hope I am not offending anybody with a cross-post.

Following some literature I was able write the code below to dynamically allocate a two dimensional array. I made the attempt to extrapolate the code for a three dimensional array. The code below for the 3-D array compiles, but gives me a fatal run-time error. Since the 3-D array is not used anywhere in the code (I am just setting it up for now), the run-time error must come from the algorithm I am using to allocate. Evidently, I don't fully understand what is going on. I appreciate any help I can get.

Thanks, Jeff

Code:
```/*******TWO DIMENSIONAL ARRAY*******/
int nx,ny;
struct GRID
{
float	x1;
float	y1;
float	x2;
float	y2;
};
GRID **grid2, *grid1;

nx = 8;
ny = 4;
grid1 = new GRID[nx*ny];
grid2 = new GRID * [nx];
for (i=0; i<nx; i++)
grid2[i] = &(grid1[i*ny]);  // Sets up a 2-D array with dimension grid[8][4]

/*******THREE DIMENSIONAL ARRAY*******/
int ndt,nx,ny;
struct CELL
{
float	height;
int	col;
};
CELL ***cell3,**cell2, *cell1;

ndt = 100;
nx = 8;
ny = 4;
cell1 = new CELL[ndt*nx*ny];
cell2 = new CELL * [ndt*nx];
cell3 = new CELL ** [ndt];
for (t=0; t<ndt; t++)
cell2[t] = &(cell1[(t*nx)]);
for (t=0; t<ndt; t++)
for (i=0; i<nx; i++)
cell3[t][i] = &(cell2[(t*nx)][(i*ny)]);  // Sets up a 3-D array with dimension cell[100][8][4]```

3. Try this
Code:
```#include <iostream>
#include <iomanip>
using namespace std;

/* make int a[max_x][max_y][max_z] */
int ***make3d ( int max_x, int max_y, int max_z ) {
int ***px = new int**[max_x];
int  **py = new int* [max_x * max_y];
int   *pz = new int  [max_x * max_y * max_z];
int rx, ry, rz;

for ( rx = 0 ; rx < max_x ; rx++ ) {
px[rx] = py;
py += max_y;
for ( ry = 0 ; ry < max_y ; ry++ ) {
px[rx][ry] = pz;
pz += max_z;
for ( rz = 0 ; rz < max_z ; rz++ ) {
px[rx][ry][rz] = rx + ry + rz;
}
}
}

return px;
}

void show ( int ***a, int max_x, int max_y, int max_z ) {
int rx, ry, rz;
for ( rx = 0 ; rx < max_x ; rx++ ) {
for ( ry = 0 ; ry < max_y ; ry++ ) {
for ( rz = 0 ; rz < max_z ; rz++ ) {
cout << setw(4) << a[rx][ry][rz];
}
cout << endl;
}
cout << "--" << endl;
}
}

void free3d ( int ***a ) {
delete [] a[0][0];
delete [] a[0];
delete [] a;
}

int main ( ) {
int ***a = make3d ( 2, 3, 4 );
show ( a, 2, 3, 4 );
free3d ( a );
return 0;
}```
If this is C++, consider using say vectors.