I am trying to adapt this existing SO answer, for assigning values into a 3 dimensional structure. I'd like to
- Define an
int ***a3d
- Call
fill_array(int ***arr, int levels, int rows, int zIdx)
- Print one of the values in the array
Here's an attempt based on 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]);
}
Unfortunately, I get
$ ./a.out
Segmentation fault (core dumped)