#include<stdarg.h> //标准头文件,提供宏va_start、va_arg、va_end #include<stdlib.h> #include<stdio.h> #define MAX_ARRAY_DIM 8 //假设数组维数的最大值为8 #define OVERFLOW -2 #define UNDERFLOW -3 #define ERROR 0 #define OK 1 typedef int Status; typedef struct { int *base; //数组元素基址,假设数组类型为int int dim; //数组维数 int *bounds; //数组维界基址 int *constants; //数组映射函数常量基址 }Array; Status InitArray(Array *A,int dim,...); Status Locate(Array A,va_list ap,int *off); Status Assign(Array *A,int e,...); Status DestroyArray(Array *A); void main() { //int off; //va_list ap; int e; Array array,*arr=&array; InitArray(arr,2,1,2); Assign(arr,1,2,3); Value(array,&e); printf("%d",e); getchar(); getchar(); } Status InitArray(Array *A,int dim,...) { int elemtotal,i; va_list ap; if (dim<1||dim>MAX_ARRAY_DIM) //判断维数是否在限制之内。如果不在之内,则返回错误 { return ERROR; } A->dim=dim; //数组标识维数信息 if (!(A->bounds=(int *)malloc(dim*sizeof(int)))) //动态分配维数的大小。返回维数的首地址 { exit(OVERFLOW); } elemtotal=1; va_start(ap,dim); //存放变长参数表信息的数组。 for(i=0;i<dim;i++) { A->bounds[i]=va_arg(ap,int); if (A->bounds[i]<0) { return UNDERFLOW; } elemtotal*=A->bounds[i]; } va_end(ap); if(!(A->base=(int*)malloc(elemtotal*sizeof(int)))) { exit(OVERFLOW); } if (!(A->constants=(int *)malloc(dim*sizeof(int))))//求映像函数的常数ci,并存入A->constants[i-1],i=1,...,dim; { exit(OVERFLOW); } A->constants[dim-1]=1; for (i = dim-2; i>0; --i) { A->constants[i]=A->bounds[i+1]*A->constants[i+1]; //ci=b(i+1)*c(i+1) } return OK; } Status Locate(Array A,va_list ap,int *off) { int i,ind; *off=0; for (i = 0; i <A.dim; i++) { ind=va_arg(ap,int); if (ind<0||ind>=A.bounds[i]) { return OVERFLOW; } *off+=A.constants[i]*ind; } return OK; } Status Assign(Array *A,int e,...) { int result,off; va_list ap; va_start(ap,e); if ((result=Locate(*A,ap,&off))<=0) { return result; } *(A->base+off)=e; return OK; } Status Value(Array A,int *e,...) { va_list ap; int off,result; va_start(ap,e); if ((result=Locate(A,ap,&off))<=0) { return result; } *e=*(A.base+off); } Status DestroyArray(Array *A) { if (!A->base) { return ERROR; } free(A->base); A->base=NULL; if (!A->bounds) { return ERROR; } A->bounds=NULL; free(A->bounds); if (!A->constants) { return ERROR; } free(A->constants); A->constants=NULL; }