学习笔记------数据结构(C语言版)数组的顺序存储

来源:互联网 发布:js class 写法例子 编辑:程序博客网 时间:2024/04/29 13:28

//SqArray.cpp

#include"predefined.h"#include"SqArray.h"Status InitArray(Array *A,int dim,...)//若维数dim和随后的各维长度合法,则构造相应的数组A,并返回OK{int i,elemtotal;if(dim<1||dim>MAX_ARRAY_DIM)return ERROR;(*A).dim=dim;(*A).bounds=(int *)malloc(dim*sizeof(int));if(!(*A).bounds)exit(OVERFLOW);va_list ap;va_start(ap,dim);for(i=0,elemtotal=1;i<dim;i++){(*A).bounds[i]=va_arg(ap,int);if((*A).bounds[i]<0)return ERROR;elemtotal*=(*A).bounds[i];}va_end(ap);(*A).base=(ElemType *)malloc(elemtotal*sizeof(int));if(!(*A).base)exit(OVERFLOW);(*A).constants=(int *)malloc(dim*sizeof(int));(*A).constants[dim-1]=1;for(i=dim-2;i>=0;i--)(*A).constants[i]=(*A).constants[i+1]*(*A).bounds[i+1];return OK;}Status DestroyArray(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).constants)return ERROR;free((*A).constants);(*A).constants=NULL;return OK;}Status Locate(Array A,va_list ap,int *off)//若ap指示的各下标值合法,则求出该元素在A中的相对地址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;}va_end(ap);return OK;}Status Value(Array A,ElemType *e,...)//A是n维数组,e是元素变量,随后是n个下标值。//若各下标不超界,则e赋值为所指定的A的元素值,并返回OK。{int off,result;va_list ap;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,...)//A是n维数组,e为元素变量,随后是n个下标值//若下标不超界,则将e的值赋给所指定的A的元素,并返回OK{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;}

//main.cpp

#include"predefined.h"#include"SqArray.h"int main(){Array A;int i,j,k,*p,dim=3,bound1=3,bound2=4,bound3=2;ElemType e;InitArray(&A,dim,bound1,bound2,bound3);p=A.bounds;printf("A.bounds=[");for(i=0;i<dim;i++)printf("%d ",p[i]);printf("]\n");p=A.constants;printf("A.constants=[");for(i=0;i<dim;i++)printf("%d ",p[i]);printf("]\n");printf("%d页%d行%d列矩阵元素如下:\n",bound1,bound2,bound3);for(i=0;i<bound1;i++){for(j=0;j<bound2;j++){for(k=0;k<bound3;k++){Assign(&A,i*100+j*10+k,i,j,k);Value(A,&e,i,j,k);printf("A[%d][%d][%d]=%4d     ",i,j,k,e);}printf("\n");}printf("\n");}p=A.base;printf("A=\n");for(i=0;i<bound1*bound2*bound3;i++){printf("%4d ",*(p+i));if(i%(bound2*bound3)==bound2*bound3-1)printf("\n");}DestroyArray(&A);}

//SqArray.h

typedef struct{ElemType *base;int dim;int *bounds;int *constants;}Array;Status InitArray(Array *A,int dim,...);Status DestroyArray(Array *A);Status Locate(Array A,va_list ap,int *off);Status Value(Array A,ElemType *e,...);Status Assign(Array *A,ElemType e,...);


0 0
原创粉丝点击