There are two different ways to select a 3D array. You can select it as a 1D array of pointers to (1D array of pointers to a 1D array). This can be done as follows:
int dim1, dim2, dim3; int i,j,k; double *** array = (double ***)malloc(dim1*sizeof(double**)); for (i = 0; i< dim1; i++) { array[i] = (double **) malloc(dim2*sizeof(double *)); for (j = 0; j < dim2; j++) { array[i][j] = (double *)malloc(dim3*sizeof(double)); } }
It is sometimes more appropriate to select an array as a continuous piece. You will find that many existing libraries may require the array to exist in allocated memory. The disadvantage of this is that if your array is very large, you may not have that large contiguous fragment available in memory.
const int dim1, dim2, dim3; #define ARR(i,j,k) (array[dim2*dim3*i + dim3*j + k]) double * array = (double *)malloc(dim1*dim2*dim3*sizeof(double));
To access the array, you simply use the macro:
ARR(1,0,3) = 4;
Il-bhima
source share