#include
#include
#include
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSe 0
#endif
#ifndef OK
#define OK 0
#endif
#ifndef ERROR
#define ERROR 1
#endif
#define MAX_ARRAY_DIM 8
typedef int Status;
typedef int ElemType;
typedef struct{
ElemType *base;
int dim;
int *bounds;
int *constants;
}Array;
Array A;
va_list ap;
Status InitArray(Array *A, int dim, ...);
Status Assign(Array *A, ElemType e, ...);
Status Value(Array *A, ElemType *e, ...);
Status DestroyArray(Array *A);
Status InitArray(Array *A, int dim, ...)
{
int i;
int elemtotal;
if(dim < 1 || dim > MAX_ARRAY_DIM) return ERROR;
A->dim = dim;
A->bounds = (int *)malloc(dim*sizeof(int));
if(A->bounds == NULL){
printf("alloc memory for bounds failure.\n");
return ERROR;
}
elemtotal = 1;
va_start(ap, dim);
for(i = 0; 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(ElemType));
if(A->base == NULL){
printf("alloc memory for base failure.\n");
return ERROR;
}
A->constants = (int *)malloc(dim * sizeof(int));
if(A->constants == NULL){
printf("alloc memory for constatns failure.\n");
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)
{
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;
A->dim = 0;
return OK;
}
Status Value(Array *A, ElemType *e, ...)
{
va_list ap;
int result;
int off;
va_start(ap, e);
result = Locate(A, ap, &off);
if(result == ERROR) return ERROR;
*e = *(A->base + off);
return OK;
}
Status Locate(Array *arr, va_list list, int *off)
{
int i;
int temp;
*off = 0;
for(i = 0; i < arr->dim; i++){
temp = va_arg(list, int);
if(temp < 0 || temp >= arr->bounds[i])return ERROR;
*off += temp * arr->constants[i];
}
return OK;
}
Status Assign(Array *A, ElemType e, ...)
{
int result;
int off;
va_start(ap, e);
if((result = Locate(A, ap, &off)) < 0) return result;
*(A->base + off) = e;
va_end(ap);
return OK;
}
int
main(void)
{
int temp;
InitArray(&A, 2, 2, 2);
Assign(&A, 3, 1, 1);
Value(&A, &temp, 1, 1);
printf("%d.\n", temp);
DestroyArray(&A);
return OK;
}
数组的顺序表示和C语言实现
最新推荐文章于 2023-03-23 17:21:56 发布
2963

被折叠的 条评论
为什么被折叠?



