简体   繁体   中英

3d dimensional array with malloc and calloc?

I am trying to make an arrangement with dynamic memory, 3-dimensional, my code is as follows:

typedef unsigned char matrix;

matrix ***mat(int n, int b)
{
    matrix ***temp = (matrix ***)malloc(n*sizeof(matrix**));
    for(int i=0; i<n; i++)
    {
        temp[i] = (matrix **)malloc(b*sizeof(matrix *));
        for(int j = 0; j < b; j++)
            temp[i][j]= (matrix *)malloc(b*sizeof(matrix));
    }
    return temp;
}
int main()
{ 
    matrix ***M2 = mat(3,2);
    for(int i=0; i<3; i++)
    {
        for(int j=0; j<2; j++)
        {
            for(int k=0; k<2; k++)
            {
                printf(" %d", M2[i][j][k]);
            }
            printf("\n");
        }
        printf("\n");
    }
    return 0;
}

when I run the program I have a segment violation, someone can tell me what the error is, since I can not visualize

I guess in the most nested for loop (the j one) the variables are messed in declaration for(int j = 0; i < b; i++) . Try j for all

您必须更正 mat 函数中嵌套 for 循环内的 j 计数器,这是正确的:
for(int j = 0; j < b; j++)

Usually I will do this kind of thing in FORTRAN, personally I like write the algorithm involving high dimensional array in FORTRAN as a library, and do the flow control staff in C. While 3D is still easily manageable in C, you need really careful with the pointers, here is a working example, it's valgrind clean.

#include <stdio.h>
#include <stdlib.h>

float ***myarray(int l, int m, int n)
{
    float **ptr = malloc(sizeof(float*)*(l+l*m));
    float *data = malloc(sizeof(float)*l*m*n);
    float **p1 = ptr, **p2 = ptr+l;
    for(int i=0; i<l; i++) {
        p1[i] = (float*)(p2+i*m);
        for(int j=0; j<m; j++)
            p2[i*m+j] = data+(i*m+j)*n;
    }
    return (float***)ptr;
}

void myfree(float ***a)
{
    free(a[0][0]);
    free(a);
}

int main()
{
    float ***array = myarray(4,3,2);
    for(int i=0; i<4; i++)
        for(int j=0; j<3; j++)
            for(int k=0; k<2; k++)
                array[i][j][k] = i+j+k;
    myfree(array);
    return  0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM