Allocating contiguous memory for a 3D array in C

£可爱£侵袭症+ 提交于 2019-12-04 22:33:11

Since you are using C, I would suggest that you use real multidimensional arrays:

int (*a)[sz[1]][sz[2]] = calloc(sz[0], sizeof(*a));

This allocates contiguous storage for your 3D array. Note that the sizes can be dynamic since C99. You access this array exactly as you would with your pointer arrays:

for(int i = 0; i < sz[0]; i++) {
    for(int j = 0; j < sz[1]; j++) {
        for(int k = 0; k < sz[2]; k++) {
            a[i][j][k] = 42;
        }
    }
}

However, there are no pointer arrays under the hood, the indexing is done by the magic of pointer arithmetic and array-pointer-decay. And since a single calloc() was used to allocate the thing, a single free() suffices to get rid of it:

free(a);    //that's it.

You can do something like this:

int ***allocateLinearMemory(int x, int y, int z)
{
    int *p = (int*) malloc(x * y * z * sizeof(int));
    int ***q = (int***) malloc(x * sizeof(int**));
    for (int i = 0; i < x; i++)
    {
        q[i] = (int**) malloc(y * sizeof(int*));
        for (int j = 0; j < y; j++)
        {
            int idx = x*j + x*y*i;
            q[i][j] = &p[idx];
        }
    }
    return q;
} 

void deallocateLinearMemory(int x, int ***q)
{
    free(q[0][0]);
    for(int i = 0; i < x; i++)
    {
        free(q[i]);
    }
    free(q);    
}

I use it and works fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!