# 数组的顺序表示与实现

D={aj1j2...jn|n(>0)称为数组的维数,bi是数组第i维的长度,ji是数组元素的第i维下标,aj1j2...jn (-ElemSet}

Ri={<aj1...ji...jn,aj1...ji+1 ...jn>|
0<=jk<=bk-1,1<=k<=n且k<>i,
0<=ji<=bi-2,aj1...ji...jn,
aj1...ji+1 ...jn(-D,i=2,...n}

InitArray(&A,n,bound1,...,boundn)

DestroyArray(&A)

Value(A,&e,index1,...,indexn)

Assign(&A,e,index1,...,indexn)

a00 a01 a02 ... a0,n-1
a10 a11 a12 ... a1,n-1
... ... ... ... ...
am-1,0 am-1,1 am-1,2 ... am-1,n-1

A0 a00 a01 a02 ... a0,n-1
a10 a11 a12 ... a1,n-1
... ... ... ... ...
am-1,0 am-1,1 am-1,2 ... am-1,n-1
A1
...
Am

a00 a01 a02 ... a0,n-1 a10 a11 a12 ... a1,n-1 ... am-1,0 am-1,1 am-1,2 ... am-1,n-1

#include<stdarg.h>
#define MAX_ARRAY_DIM 8
typedef struct {
ElemType *base;
int dim;
int *bounds;
int *constants;
}Array;
Status InitArray(Array &A,int dim,...);
Status DestroyArray(Array &A);
Status Value(Array A,ElemType &e,...);
Status Assign(Array &A,ElemType e,...);

Status InitArray(Array &A,int dim,...){
if(dim<1||dim>MAX_ARRAY_DIM) return ERROR;
A.dim=dim;
A.bounds=(int *)malloc(dim *sizeof(int));
if(!A.bounds) exit(OVERFLOW);
elemtotal=1;
va_start(ap,dim);
for(i=1;i<dim;++i){
A.bounds=va_arg(ap,int);
if(A.bounds<0) return UNDERFLOW;
elemtotal*=A.bounds;
}
va_end(ap);
A.base=(ElemType *)malloc(elemtotal*sizeof(ElemType));
if(!A.base) exit(OVERFLOW);
A.constants=(int *)malloc(dim*sizeof(int));
if(!A.constants) exit(OVERFLOW);
A.constants[dim-1]=1;
for(i=dim-2;i>=0;--i)
A.constants=A.bounds[i+1]*A.constants[i+1];
return OK;
}
Status DestoyArray(Array &A){
if(!A.base) return ERROR;
free(A.base); A.base=NULL;
if !(A.bounds) return ERROR;
free(A.bounds); A.bounds=NULL;
if!(A.constatns) return ERROR;
free(A.constants); A.constants=NULL;
return OK;
}
Status Locate(Array A,va_list ap,int &off){
off=0;
for(i=0;i<A.dim;++i){
ind=va_arg(ap,int);
if(ind<0||ind>=A.bounds) return OVERFLOW;
off+=A.constants*ind;
}
return OK;
}
Status Value(Array A,ElemType &e,...){
va_start(ap,e);
if((result=Locate(A,ap,off))<=0 return result;
e=*(A.base+off);
return OK;
}
Status Assign(Array &A,ElemType e,...){
va_start(ap,e);
if((result=Locate(A,ap,off))<=0) return result;
*(A.base+off)=e;
return OK;
}