美文网首页
C语言表示n维数组

C语言表示n维数组

作者: obsession_me | 来源:发表于2018-06-01 21:30 被阅读0次
    #include <stdarg.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    #define MAX_ARRAY_DIM 8
    typedef int ElemType;
    
    typedef struct{
        ElemType *base; // 数组元素基址
        int dim;        // 维度
        int *bounds;    // 数组维界基址
        int *constants; // 数组映像函数常量基址
    }array;
    
    void init(array *a, int dim, ...){
        // 判断维数dim和随后的各维度长度是否合法,合法则构建数组
        if (dim <1||dim>MAX_ARRAY_DIM) exit(1); // error
        a->dim = dim;
        a->bounds = malloc(a->dim*sizeof(int));
        if(!a->bounds) exit(1);  // malloc memory error
        // 若各维度长度合法,则存入a->bounds,并求出a中的元素总数
        int elemTotal = 1;
        va_list ap;
        va_start(ap, dim);
        for (int i=0; i<a->dim; ++i){
            a->bounds[i] = va_arg(ap, int);
            if (a->bounds[i]<0) return exit(1); //can't assign negative values
            elemTotal *= a->bounds[i];
        }
        va_end(ap);
        a->base = malloc(elemTotal*sizeof(ElemType));
        if (!a->base) exit(1); // allocte memory failure, then exit
        // 下一步则是求映像函数常数,以简化计算
        a->constants = malloc(dim*sizeof(ElemType));
        if (!a->constants) exit(1); // error
        a->constants[dim-1] = 1;
        for (int i=dim-2; i>=0; --i){
            a->constants[i] = a->bounds[i+1]*a->constants[i+1];
        }
    }
    
    void destory(array *a){
        if !(a->base) exit(1);  // empty
        free(a->base);
        if !(a->bounds) exit(1);
        free(a->bounds);
        if !(a->constants) exit(1);
        free(a->constants);
    }
    
    void locate(array a, va_list ap, int *off){
        // 若ap指示的下标合法,则求出该元素在a中的相对地址off
        *off = 0;
        for (int i=0; i<a->dim; ++i){
            int ind = va_arg(ap, int);
            if (ind <0|| ind>=a->bounds[i]) exit(1); // excess
            off += a->constants[i]*ind;
        }
    }
    
    
    void main(){
        array a;
        init(&a, 3, 4, 4, 4);
    }
    

    相关文章

      网友评论

          本文标题:C语言表示n维数组

          本文链接:https://www.haomeiwen.com/subject/rcxlsftx.html