Array in order to store representations and implementations:
#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,...);
The basic operation of the algorithm description:
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;
}