教材:严版数据结构

IDE: VS2015

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#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");
}