//數組的順序存儲表示 //楊鑫 #include#include #include #include #define OK 1 #define ERROR 0 #define UNDERFLOW 2 #define MAX_ARRAY_DIM 8 typedef int Status; typedef int ElemType; typedef struct { ElemType *base; //數組的實體 int dim; //數組維數 int *bounds; //根據下文bound應該是bounds,數組各維的長度 int *constants; //數組映像函數常量的基址 }Array; //數組初始化 Status InitArray(Array *A, int dim,...) { int elemtotal=1,i; va_list ap; if (dim < 1 || dim > MAX_ARRAY_DIM) return ERROR; A->dim = dim; A->bounds = (int*)malloc(dim*sizeof(int)); if(!A->bounds) return ERROR; va_start(ap,dim); for(i=0;i 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) return ERROR; A->constants=(int*)malloc(dim*sizeof(int)); if(!A->constants) return ERROR; 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 DestroyArray(Array *A) { free(A->base); free(A->bounds); free(A->constants); return OK; } //找到A的地址 Status Locate(Array A,va_list ap,int *off) { int ind, i; *off=0; for(i=0;i=A.bounds[i]) return ERROR; *off+=A.constants[i]*ind; } return OK; } //賦值把值賦值給數組A Status Assign(Array *A,ElemType e,...) { va_list ap; Status result; int i,j,k; int off; va_start(ap,e); if((result=Locate(*A,ap,&off))<0) return result; *(A->base+off)=e; va_end(ap); return OK; } //把值賦值給數組A中指定的元素e Status Value(Array A,ElemType *e,...) { int off; Status result; va_list ap; va_start(ap,e); if ((result=Locate(A,ap,&off))<0) return result; *e=*(A.base+off); va_start(ap,e); return OK; } int main() { int i,j,k; Array A; ElemType e; A.dim=3; InitArray(&A,A.dim,2,2,2); printf("這是一個 %d 維的數組!\n",A.dim); printf("數組每個維度的大小:\n"); for (i=0;i
如圖: