贴出一个我自己常用的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;
}
|