学習ノート------データ構造(C言語版)配列の順序格納
2233 ワード
//SqArray.cpp
//main.cpp
//SqArray.h
#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=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.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
//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,...);