[GRASS-user] GRASS Dynamic allocation of multi dimensional array
Glynn Clements
glynn at gclements.plus.com
Sat Aug 9 16:19:40 EDT 2008
gianluca massei wrote:
> could anybody help me to declare a 3D matrix in C GRASS module. I've to
> load several raster map with same location but I've an error in run time
> if I declare with G_malloc/G_calloc like that:
> double ***mat;
>
> mat=(double***)G_malloc(ndimension*(sizeof(double));
To implement variable-size multi-dimensional arrays in C, you have two
options:
1. Allocate a single contiguous block and calculate the indices
yourself, e.g.:
double *data = G_malloc(width * height * depth * sizeof(double));
#define DATA(x,y,z) (data[((z) * height + (y)) * width + (x)])
...
/* read element */
v = DATA(x,y,z);
/* write element */
DATA(x,y,z) = v;
2. Create arrays of pointers:
int i, j;
double ***data = G_malloc(depth * sizeof(double **));
for (j = 0; j < depth; j++)
{
data[j] = G_malloc(height * sizeof(double *));
for (i = 0; i < height; i++)
data[j][i] = G_malloc(width * sizeof(double));
}
...
/* read element */
v = data[z][y][x];
/* write element */
data[z][y][x] = v;
--
Glynn Clements <glynn at gclements.plus.com>
More information about the grass-user
mailing list