C 语言的动态多维数组

贴出一个我自己常用的C 语言的动态多维数组。欢迎大家指正。

#include <stdio.h>
#include <stdarg.h>
 
 
char * mnew (unsigned long typesize, unsigned short dimention, ...)
/*=============================================================================
    by Kan ZENG, 2000.02.16.    tested on 2000.02.16
    Ocean Remote Sensing Institute
    Ocean University of Qingdao
 
    mnew and mdelete are couple of routines to deal with allocing and freeing
    the memory for multi-dimention array.
para:
    typesize -- the size in byte of one element
    dimention - the number of dimention
    ...       - the variational argument list. each one MUST BE long interger.
                The further right, the lower the dimention is.
 
    p         - the pointer which was alloced by mnew
 
Return:
    mnew return the first address of alloced memory block if successful or NULL
    if fail.
 
Usage:
    if a double type 3D dynamical array is required, the method to using mnew as
    following:
    double ***myarray =
    (double ***) mnew(sizeof(double),3, (long)n3, (long)n2, (long)n1);
 
    After that, you can refer the element as usual:
      e.g.   myarray[4][2][5]=45.77;
=============================================================================*/
{
    va_list vl;
    long i, j;
    long prdt1, prdt2;
    long *dim;
    char *res;
 
    if (dimention <1) return NULL;
 
    dim= new long[dimention];
 
    // dimention is the last argument specified; all
    //   others must be accessed using the variable-
    //   argument macros.
    va_start( vl, dimention);
 
    // Step through the list.
    for(i=dimention-1; i>=0; i--)
        dim[i]=va_arg( vl, long );
    va_end( vl );
 
    if (dimention==1) {
        res = new char[dim[0]];
        delete[] dim;
        return res;
    }
 
    prdt1=dim[1]; prdt2=dim[0]*dim[1];
    for(i=2; i<dimention; i++) {
        ++prdt1 *= dim[i];
          prdt2 *= dim[i];
    }
 
    if ((res=new char[prdt1*sizeof(void *)+prdt2*typesize])==NULL) {
        delete[] dim;
        return NULL;
    }
 
    char *p;
    void **q2, **p1, **p2;
 
    p = res+prdt1*sizeof(void *) ;
    q2 = (void **)p;
    prdt2 /= dim[0];
    q2    -= prdt2;
 
    p2 = q2;
    for(j=0; j<prdt2; j++) {
        *p2=p;
        p2++;
        p+=dim[0]*typesize;
    }
 
    for(i=1; i<(dimention-1); i++) {
        p1=q2;
        prdt2 /= dim[i];
        q2 -= prdt2;
        p2 = q2;
        for(j=0; j<prdt2; j++) {
            *p2=p1;
            p2++; p1+=dim[i];
        }
    }
 
    delete[] dim;   
    return res;
}
 
 
 
void mdelete(void * p)
{
    if (p==NULL) return;
    delete[] (char *)p;
    p=NULL;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值