C语言为四维数组申请动态内存空间的方法(二)

尝试了用堆栈的方式为四维数组申请动态内存空间,并将申请内存的操作封装成了子函数,方便在主程序中使用。希望对大家有用。代码如下:

#include 
#include 

float**** alloc4float(int n1,int n2,int n3,int n4)
{
    int i,j,k;

    float**** result = NULL;

    if((n1 > 0) && (n2 > 0) && (n3 > 0) && (n4 > 0) )
    {
        float*** p3 = NULL;
        float** p2  = NULL;
        float* p1   = NULL;

        result = (float****)malloc(n4 * sizeof(float***));
        p3 = (float***)malloc(n4*n3* sizeof(float**));
        p2 = (float**)malloc(n4*n3*n2* sizeof(float*));
        p1 = (float*)malloc(n4*n3*n2*n1* sizeof(float));

        if((result != NULL) && (p1 != NULL) && (p2 != NULL)&& (p3 != NULL))
        {
            for(i = 0;i < n4;i++)
            {
                result[i] = p3 + i * n3;
                for (j = 0;j < n3;j++)
                {
                    result[i][j] = p2 + j * n2;
                    for (k = 0;k < n2;k++)
                    {
                        result[i][j][k] = p1 + k * n1;
                    }
                }
                p1 = p1 + n3*n2*n1;
            }
        }else
        {
            free(result);
            free(p1);
            free(p2);
            free(p3);
            result = NULL;
            p1 = NULL;
            p2 = NULL;
            p3 = NULL;
        }
    }
    return result;
}

void free4float(float**** p4)
{
    if(*p4 != NULL)
    {
        if(**p4 != NULL)
        {
            free(**p4);
            **p4 = NULL;
        }
        free(*p4);
        *p4 = NULL;
    }
    free(p4);
    p4 = NULL;
}



int main()
{
    int i,j,k,l;
    float value=1;
    int nx,ny,nz,nt;
    float ****dat;

    nx=5;
    ny=10;
    nz=15;
    nt=20;

    dat = alloc4float(nt,nz,ny,nx);

    for (i = 0; i < nx; i++)
    {
        for (j = 0; j < ny; j++)
        {
            for (k = 0; k < nz; k++)
            {
                for (l = 0; l < nt; l++)
                {
                    dat[i][j][k][l] = value++;
                    printf("dat[%d][%d][%d][%d]=%p\n",i,j,k,l,&dat[i][j][k][l]);
                }
            }
        }
    }

    if(dat != NULL)
    {
        free4float(dat);
    }

    printf("End!\n");
    return 0;
}

如有问题,欢迎留言~~

你可能感兴趣的:(C语言专栏)