首页 > 解决方案 > C语言中的内存分配——3D数组

问题描述

我想为 C 语言中的数据立方体分配内存。我的意思是,我需要分配一个 3D 数组。但是,我的代码返回了分段错误,我不知道为什么。

我相信我的循环是正确的,但事实是,我的代码不起作用。

这是我的代码:

int malloc3dfloat(float ****array, int q, int r, int s) {
    // allocate the q*r*s contiguous items 
    float *p = (float *) malloc(q*r*s*sizeof(float));
    if (!p) return -1;

    // allocate the row pointers into the memory 
    (*array) = (float ***) malloc(q*sizeof(float**));
    if (!(*array)) {
       free(p);
       return -1;
    }
    for (int i=0; i<q; i++)
    {
        (*array)[i] = (float **) malloc(r*sizeof(float*));
        if (!(*array[i])) 
        {
        free(p);
        return -1;
        }
    }

    //set up the pointers into the contiguous memory
    for (int i=0; i<q; i++)
    {
        for (int j=0; j<r; j++)
        { 
            (*array)[i][j] = &(p[(i*r+j)*s]);
        }
    }

    return 0;
}

标签: cmemorymalloc

解决方案


只需将可变长度数组与动态存储一起使用。

float (*array)[r][s]=calloc(q, sizeof *array);

就这样!

现在使用array[i][j][k]语法来访问单个元素。


推荐阅读