使用C中的值填充指针中的3D数组

时间:2014-08-21 17:52:47

标签: c arrays pointers

我正在尝试调整this existing SO answer,以便将值分配到三维结构中。我想

  1. 定义int ***a3d
  2. 致电fill_array(int ***arr, int levels, int rows, int zIdx)
  3. 打印数组中的一个值
  4. 以下是基于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)
    

0 个答案:

没有答案