www.pudn.com > datastructor.rar > Array.c


#include  
#include  
#include  
 
#define MAX_ARRAY_DIM   8 //假设数组维数的最大值为8  
typedef enum {ERROR = -2,OVERLOW,FALSE, TRUE, OK} Status; 
typedef int ElemType; 
typedef struct{ 
    ElemType* base;       //数组元素基址,由InitArray分配  
    int     dim;          //数组维数  
    int*    bounds;       //数组维界基址,由InitArray分配  
    int*    constants;    //数组映像函数常量基址,由InitArray分配  
}Array; 
 
Status InitArray(Array* A, int dim,...) { 
    //若维数dim和各维长度合法,则构造相应的数组A,并返回OK  
    if(dim<1 || dim>MAX_ARRAY_DIM) return ERROR; 
    A->dim = dim; 
    A->bounds = (int*) malloc(dim*sizeof(int)); 
    if(!A->bounds) exit(OVERLOW); 
    //若各维长度合法,则存入A.bounds,并求出A的元素总数elemtotal  
    int elemtotal = 1; 
    int i; 
    va_list ap; 
     
    va_start(ap, dim); 
    for(i = 0; i < dim; ++i){ 
        A->bounds[i] = va_arg(ap, int); 
        if(A->bounds[i] < 0) return OVERLOW; 
        elemtotal *= A->bounds[i]; 
    } 
    va_end(ap); 
     
    A->base = (ElemType*) malloc(elemtotal * sizeof(ElemType)); 
    if(!A->base) exit(OVERLOW); 
     
    A->constants = (int*) malloc(dim*sizeof(int)); 
    if(!A->constants) exit(OVERLOW); 
     
    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) { 
    //销毁数组A  
    if(A->base) free(A->base); 
    if(A->bounds) free(A->bounds); 
    if(A->constants) free(A->constants); 
    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 OVERLOW; 
        *off += A->constants[i] * ind; 
    } 
    return OK; 
}                      
         
Status Value(Array* A, ElemType *e, ...) { 
    //A是n维数组,e为元素变量,随后是n个下标值 
    //若各下标不超界,则e赋值为所指定的A的元素值,并返回OK  
    va_list ap; 
    int off; 
    Status result; 
     
    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  
    va_list ap; 
    int off; 
    Status result; 
     
    va_start(ap, e); 
    if((result = Locate(A, ap, &off)) <= 0) return result; 
    *(A->base + off) = e; 
    return OK; 
}     
     
int main() 
{ 
    Array array1; 
    int i, j, k=1; 
    int m, n; 
    ElemType e; 
     
    printf("请输入数组的第1、2维的维数:");  
    scanf("%d%d", &i, &j); 
    printf("输出数组: \n");  
    InitArray(&array1, 2, i, j); 
    for(m = 0; m < i; ++m)  
        for(n = 0; n < j; ++n){ 
            Assign(&array1, k, m, n); 
            Value(&array1, &e, m, n); 
            printf("%d\t", e); 
            if(k%8 == 0) printf("\n"); 
            ++k; 
    } 
    DestroyArray(&array1); 
     
    system("pause"); 
    return 0; 
}