我正在尝试调整this existing SO answer,以便将值分配到三维结构中。我想
int ***a3d
fill_array(int ***arr, int levels, int rows, int zIdx)
以下是基于the other SO answer的尝试:
#include <stdio.h>
#include <stdlib.h>
#define ZALLOC(item, n, type) if ((item = (type *)calloc((n), sizeof(type))) == NULL) \
fatalx("Unable to allocate %d unit(s) for item\n", n)
static void fatalx(const char *str, size_t n)
{
fprintf(stderr, "%s: %zu\n", str, n);
exit(1);
}
static void fill_array(int ***arr, int levels, int rows, int zIdx){
int count = 0;
int i, j, k;
ZALLOC(arr, levels, int **);
for (i = 0; i < levels; i++)
{
int **data;
ZALLOC(data, rows, int *);
arr[i] = data;
for (j = 0; j < rows; j++)
{
int *entries;
ZALLOC(entries, zIdx, int);
arr[i][j] = entries;
for (k = 0; k < zIdx; k++)
{
arr[i][j][k] = count++;
}
}
}
}
int main( int argc, char** argv )
{ /* dimensions of the array */
int d1 = 800;
int d2 = 600;
int d3 = 3;
/* define the 3D array */
int ***a3d;
/* fill it with values */
fill_array(a3d,d1,d2,d3);
/* print one value in the 3d array */
printf("Example value is %i\n", a3d[5][5][1]);
}
不幸的是,我得到了
$ ./a.out
Segmentation fault (core dumped)