数组——顺序存储结构

     严版数据结构93页。
     IDE:VS2015

 
#include<iostream>
#include<stdarg.h>

using namespace std;

#define MAX_ARRAY_DIM 8
#define ElemType int
#define Status int
#define ERROR 0
#define OK 1
#define FALSE 0
#define TRUE 1



typedef struct {
	ElemType *base;//数组元素基址
	int dim;//数组维数
	int *bounds;//数组维界基址
	int *constants;//数组映像函数常量基址
}Array;

Status InitArray(Array &A, int dim,...)
{
	if (dim<1 || dim>MAX_ARRAY_DIM)
		return ERROR;
	A.dim = dim;
	A.bounds = (int *)malloc(dim*sizeof(int));
	va_list ap;
	
	int elemtotal = 1;//A的元素总数
	va_start(ap, dim);
	for (int i = 0; i < dim; ++i)
	{
		A.bounds[i] = va_arg(ap, int);
		if (A.bounds[i] < 0)
			return UNDERFLOW;
		elemtotal *= A.bounds[i];
	}
	va_end(ap);
	A.base = (ElemType *)malloc(elemtotal * sizeof(ElemType));
	
	A.constants = (int *)malloc(dim * sizeof(int));
	
	A.constants[dim - 1] = 1;
	for (int 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 = ERROR;
	if (!A.bounds)
		return ERROR;
	free(A.bounds);
	A.bounds = NULL;
	if (!A.constants)
		return ERROR;
	free(A.constants);
	A.constants = NULL;
	return OK;
}

Status Locate(Array &A, va_list ap, int &off)//若ap指示的各下标合法,则求出该元素在A中的相对地址off
{
	off = 0;
	int ind;
	for (int 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;
}

Status Value(Array A, ElemType *e, ...)
{
	va_list ap;
	
	va_start(ap, e);
	Status result;
	int off;
	if ((result = Locate(A, ap, off)) <= 0)
		return result;
	*e = *(A.base + off);
	va_end(ap);
	return OK;
}


Status Assign(Array &A, ElemType e, ...)
{
	va_list ap;
	va_start(ap, e);
	Status result;
	int off;
	if ((result = Locate(A, ap, off)) <= 0)
		return result;
	*(A.base + off) = e;
	va_end(ap);
	return OK;
}

void main()
{
	Array A;
	ElemType e;
	InitArray(A, 3, 2, 3, 4);
	Assign(A, 100, 1, 2, 3);
	if (Value(A, &e,1, 2, 3) == OK)
		cout << "输出e的值:" << e << endl;
	if (DestroyArray(A) == OK)
		cout << "数组A销毁成功!"<< endl;
	system("pause");
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值