第五章数组和广义表——5.2:数组的顺序表示和实现

第五章数组和广义表——5.2:数组的顺序表示和实现

我们看看数组的顺序存储表示

#include<stdarg.h>

#define maxx 8
typedef struct
{
	elemtype* base;
	int dim;
	int* bound;
	int* constants;
}array;

下面是部分基本算法

若维数和随后的各维长度合法没构建数组a

Status initarray(array& a, int dim, ...)
{
	if (dim<1 || dim>maxx) return error;
	a.dim = dim;
	a.bounds = (int*)malloc(dim * sizeof(int));
	if (!a.bounds) exit(overflow);
	elemtotal = 1;
	va_start(ap, dim);
	for (i = 0; i < dim; ++i)
	{
		a.bounds[i] = va_arg(ap, int);
		if (a.bounds[i] < 0) reutnr UNDERFLOW;
		elemtotal *= a.bounds[i];
	}
	va_end(ap);
	a.base = (elemtype*)malloc(elemtotal * sizeof(elemtype));
	if (!base) exit(overflow);
	a.constants = (int*)malloc(dim * sizeof(int));
	if (!a.constants)exit(overflow);
	a.contants[dim - 1] = 1;
	for (i = dim - 2; i >= 0; i--)
	{
		a.contants[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;
	return ok;
}

求出元素在a中的相对位置

Status locate(array a, va_list ap, int& off)
{
	off = 0;
	for (i = 0; i < a.dim; ++i)
	{
		ind = va_arg(ap, int);
		if (ind < 0 || ind >= a.bounds[i]) return overflow;
		off += a.constants[i] * ind;
	}
	return ok;
}

A是n维数组,e维元素变量,随后是n个下标值。

Status value(array a, elemtype& e, ...)
{
	va_start(ap, e);
	if ((result = locate(a, ap, off)) <= 0) return result;
	e = *(a.base + off);
	return ok;
}

A是n维数组,e维元素变量,随后是n个下标值。

Status assign(array a, elemtype e, ...)
{
	va_start(ap, e);
	if ((result = locate(a, ap, off)) <= 0) return result;
	*(a.base + off) = e;
	return ok;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Harden先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值