第五章数组和广义表——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;
}