Malloc a 3-Dimensional array in C?

后端 未结 13 913
余生分开走
余生分开走 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条回答
  •  萌比男神i
    2020-11-28 07:59

    About the segfault, I am pretty sure someone else has pointed this out but just in case, there is a extra '*' in the first line of the first for loop

    for (i = 0; i < 3; i++) {
        *array[i] = malloc(3*sizeof(int*));
    //  ^ we dont want to deference array twice
        for (j = 0; j < 3; j++) {
            array[i][j] = malloc(3*sizeof(int));
        }
    }
    

    try the following:

        for (i = 0; i < 3; i++) {
            array[i] = malloc(3*sizeof(int*));
            for (j = 0; j < 3; j++) {
                array[i][j] = malloc(3*sizeof(int));
            }
        }
    

提交回复
热议问题