#include
#include
#include
#define MAX_ARRAY_DIM 8
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status;
typedef int ElemType;
typedef struct{
int dim; //存储数组的维数
ElemType* base; //存储数组的基址 由 InitArray 分配
int* constants; //contant连续的
int* bounds; //存储数组维界地址 由 InitArray 分配
}array;
下面的部分用来初始化数组
Status InitArray(array* a, int dim,… )
{
va_list ap;
int elemtotal = 1 , i = 0;
if(1 > dim || MAX_ARRAY_DIM < dim) return ERROR;
a->dim = dim;
a->bounds = (int *)malloc(dim * sizeof(int));
if(!a->bounds)
exit(OVERFLOW);
va_start(ap,dim);
for(i = 0 ; i < dim ; i++){
a->bounds[i] = va_arg(ap,int);
if(a->bounds <= 0) return ERROR;
elemtotal *= a->bounds[i]; //计算元素的总的个数
}
a->base = (ElemType *)malloc(elemtotal * sizeof(ElemType)); //分配数组的空间,为a指定基址
//为constants分配空间
a->constants = (int *)malloc(dim * sizeof(int));
if(!a->constants) exit(OVERFLOW);
/*下面的部分是整个程序中最难理解的部分,其中的constants[X]相当于第X维的单位长度,当X=1时即数组的第1维中每个单位包含的元素数,同理第2。。。一直到第n-1维,第n-1维的每个单位长度为1.*/
a->constants[dim-1] = 1;
for(i = dim -2 ; i >= 0 ; i–){
a->constants[i] = a->bounds[i+1] * a->constants[i+1];
// printf(“%d “,a->constants[i]);
}
for(i = 0 ; i < dim ; i++)
// printf(“\n%d “,a->constants[i]);
return OK;
}
//取得指定下标的偏移量
Status Locate(array* a,va_list ap,int* off)
{
int i=0,ind;
*off = 0;
for(i = 0 ; i < a->dim ; i++){
ind = va_arg(ap,int);
if(ind < 0 || ind >= a->bounds[i])return ERROR;
/*这里通过上面我们计算的那个单位长度与每维序数相乘的积累加起来即为偏移量*/
*off += a->constants[i]*ind;
}
}
//取得数组的值
ElemType Value(array* a,…)
{
va_list ap;
int off = 0;
va_start(ap,a);
if(!Locate(a,ap,&off))return ERROR;
return *(a->base+off);
}
//设置数组的值
Status set(array* a,ElemType b,…)
{
va_list ap;
int off = 0;
va_start(ap,b);
if(!Locate(a,ap,&off))return ERROR;
*(a->base+off) = b ;
return OK;
}
//释放这个数组
Status DestoryArray(array* a){
if(!a->base)return ERROR;
free(a->base);
if(!a->bounds)return ERROR;
free(a->bounds);
if(!a->constants) return ERROR;
free(a->constants);
return OK;
}
Post Views:
1,617