Malloc a 3-Dimensional array in C?

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

    This should work, you are not typecasting the return value of malloc

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

    Working Link: http://ideone.com/X2mcb8

提交回复
热议问题