Ç - 多维数组分配 [英] C - multidimensional array allocation

查看:149
本文介绍了Ç - 多维数组分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用下面的C函数来模拟一个四维阵列。除了增加额外的循环,有没有使这个功能很通用,创建n维数组的好办法?

I'm using the following C function to emulate a 4D array. Other than adding additional loops, is there a good way to make this function generic enough to create n-dimensional arrays?

double ****alloc_4D_data(int wlen, int xlen, int ylen, int zlen)
{
    int i,j,k;

    double ****ary = (jdouble****)malloc(wlen*sizeof(jdouble***));

    for (i = 0; i < wlen; i++) 
    {
        ary[i] = (jdouble***)malloc(xlen*sizeof(jdouble**));

        for (j = 0; j < xlen; j++) 
        {
            ary[i][j] = (jdouble**)malloc(ylen*sizeof(jdouble*));

            for (k = 0; k < ylen; k++) 
            {
                ary[i][j][k] = (jdouble*)malloc(zlen*sizeof(jdouble));
            }
        }
    }

    return ary;
}


推荐答案

在C语言中,多维阵列的每个元素存储在一个连续的存储区域。所以,你只需要计算所有N维的元素总数和malloc的整个内存。如:

In C language, every elements of the multi dimensional array are stored in a continual memory area. So you just need to calculate the total number of elements of all N dimensional and malloc the whole memory. Such as:

/* int *Nlen is a N length array to store every dimensional array length
 * int N is the Nlen array length indicates how many dimensions.
 */
double *alloc_ND_data(int wlen, int *Nlen, int N)
{
    int i;
    int total = 1;
    double *array;

    for(i = 0; i < N; i ++) {
    /* Every dimension should mul the next depth dimension size */ 
        total *= Nlen[i]; 
    }
    array = malloc(wlen*total*sizeof(jdouble));

    return array;
}

这篇关于Ç - 多维数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆