动态分配三维数组

来源:互联网 发布:数据库原理基本知识点 编辑:程序博客网 时间:2024/05/09 23:01

第一种是分配一块内存,使用的时候类似一维数组:

inline char * allocate_3(int c,int h,int w)

{

unsigned char *a

a=(unsigned char*) malloc(sizeof(unsigned char )*(c*h*w));
if(a==NULL) {printf("Memory is too huge, fail.\n"); getchar(); exit(0); }

    return a;


}


inline void  free_3(unsigned char *p)
{
if(p!=NULL)
{
free(p);
p=NULL;
}
}

使用:

for(int i=0;i<c;i++) 
        for(int j=0;j<h;j++) 

for(int k=0;k<w;k++)

p[i*h*w+j*w+k] = 0;

第二种是分配一块内存,并为其分配二维和三维索引:


inline unsigned char *** qx_allocu_3(int n,int r,int c,int padding=QX_DEF_PADDING)
{
unsigned char *a,**p,***pp;
    int rc=r*c;
    int i,j;
a=(unsigned char*) malloc(sizeof(unsigned char )*(n*rc+padding));
if(a==NULL) {printf("qx_allocu_3() fail, Memory is too huge, fail.\n"); getchar(); exit(0); }
    p=(unsigned char**) malloc(sizeof(unsigned char*)*n*r);
    pp=(unsigned char***) malloc(sizeof(unsigned char**)*n);
    for(i=0;i<n;i++) 
        for(j=0;j<r;j++) 
            p[i*r+j]=&a[i*rc+j*c];
    for(i=0;i<n;i++) 
        pp[i]=&p[i*r];
    return(pp);
}
inline void qx_freeu_3(unsigned char ***p)
{
if(p!=NULL)
{
free(p[0][0]);
free(p[0]);
free(p);
p=NULL;
}
}

使用:

for(int i=0;i<c;i++) 
        for(int j=0;j<h;j++) 

for(int k=0;k<w;k++)

p[i][j][k]= 0;


0 0
原创粉丝点击