Malloc a 3-Dimensional array in C?

后端 未结 13 917
余生分开走
余生分开走 2020-11-28 07:56

I\'m translating some MATLAB code into C and the script I\'m converting makes heavy use of 3D arrays with 10*100*300 complex entries. The size of the array also depends on t

13条回答
  •  情歌与酒
    2020-11-28 08:14

    In this way you can allocate only just 1 block of memory and the dynamic array behaves like the static one (i.e. same memory contiguity). You can also free memory with a single free(array) like ordinary 1-D arrays.

    double*** arr3dAlloc(const int ind1, const int ind2, const int ind3)
    {
      int i;
      int j;
      double*** array = (double***) malloc( (ind1 * sizeof(double*)) + (ind1*ind2 * sizeof(double**)) + (ind1*ind2*ind3 * sizeof(double)) );
      for(i = 0; i < ind1; ++i) {
        array[i] = (double**)(array + ind1) + i * ind2;
        for(j = 0; j < ind2; ++j) {
          array[i][j] = (double*)(array + ind1 + ind1*ind2) + i*ind2*ind3 + j*ind3;
        }
      }
      return array;
    }
    

提交回复
热议问题