C语言遍历n维数组,C语言表示n维数组

#include

#include

#include

#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; idim; ++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; idim; ++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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值