数据结构教程 第二十二课 实验五 数组实验2007-05-16
教学目的: 掌握二维数组的实现方法
教学重点: 二维数组的存储表示,二维数组的基本操作
教学难点: 二维数组的基本操作
授课内容:数组的顺序存储表示和实现:#include<stdarg.h>#define MAX_ARRAY_DIM 8typedef 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[i]=va_arg(ap,int);if(A.bounds[i]<0) return UNDERFLOW;elemtotal*=A.bounds[i];
}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[i]=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[i]) return OVERFLOW;off+=A.constants[i]*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;}