Malloc a 3-Dimensional array in C?

后端 未结 13 903
余生分开走
余生分开走 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:02

    add #include "stdlib.h" and remove the * from *array[i] and it will run when compiled in gcc 4.4.1 on Ubuntu

    also if you add print statements you can find your bugs quicker

    #include 
    #include 
    
    int main () {
      int ***array = malloc(3*sizeof(int**));
      int i, j;
    
      printf("%s\n","OK");
    
      for (i = 0; i < 3; i++) {
        printf("i = %i \n",i);
        array[i] = malloc(3*sizeof(int*));
        for (j = 0; j < 3; j++) {
          printf("i,j = %i,%i \n",i,j);
          array[i][j] = malloc(3*sizeof(int));
        }
      }
    
      array[1][2][1] = 10;
    
      return 0;
    }
    

提交回复
热议问题