C语言多维数组的实现与操作
常量和所需的头文件
#include<stdio.h>
#include<stdarg.h>
#include<stdlib.h>
#define MAX_ARRAY_DIM 8 //设置数组维数最大为8
#define ElemType int
#define ERROR -1
#define SUCCESS 1
#define OVERFLOW -2
#define UNDERFLOW -3
结构体
typedef struct {
ElemType* base;//数组元素基址,由InitArray分配
int dim;//数组维数
int* bounds;//数组维界基址,由InitArray分配
int* constants;//数组映像函数常量基址,由InitArray分配
}Array;
构造数组A
Array InitArray(Array A, int dim, ...) {
//若维数dim和各维长度合法,则构造相应的数组A
if (dim<1 || dim>MAX_ARRAY_DIM)
{
exit(ERROR);
}
A.dim = dim;
A.bounds = (int*)malloc(dim * sizeof(int));
if (!A.bounds)
{
exit(OVERFLOW);
}
//若各维长度合法,则存入A.bounds,并求出A的元素总数elemtotal
int elemtotal = 1;
va_list ap;
va_start(ap, dim);
for (int i = 0; i < dim; i++)
{
A.bounds[i] = va_arg(ap, int);
if (A.bounds[i] < 0)
{
exit(UNDERFLOW);
}
elemtotal *= A.bounds[i];
}
va_end(ap);
A.base = (ElemType*)malloc(elemtotal * sizeof(ElemType));
if (!A.base)
{
exit(OVERFLOW);
}
//求映像函数的常数ci,并存入A.constants[i-1],i=1,...,dim
A.constants = (int*)malloc(elemtotal * sizeof(ElemType));
if (!A.base)
{
exit(OVERFLOW);
}
A.constants[dim - 1] = 1;//L=1,指针的增减以元素的大小为单位
for (int i = dim - 2; i >= 0; i--)
{
A.constants[i] = A.bounds[i + 1] * A.constants[i + 1];
}
return A;
}
销毁释放数组
Array DestoryArray(Array A) {
if (!A.base)
{
exit(ERROR);
}
free(A.base);
A.base = NULL;
if (!A.bounds)
{
exit(ERROR);
}
free(A.bounds);
A.bounds = NULL;
if (!A.constants)
{
exit(ERROR);
}
free(A.bounds);
A.bounds = NULL;
return A;
}
求出元素在数组中的相对地址
int Locate(Array A, va_list ap, int off) {
//若ap指示的各下标值合法,则求出该元素在A中相对地址off
for (int i = 0; i < A.dim; i++)
{
int ind = va_arg(ap, int);
if (ind < 0 || ind >= A.bounds[i]) {
exit(OVERFLOW);
}
off += A.constants[i] + ind;
}
return off;
}
获取A相应位置值函数
int Value(Array A, ElemType e, ...) {
//A是N维数组,e为元素变量,随后是n个下标值
//若下标不超界,则e赋值为所指定的A的元素值
va_list ap;
int off = 0;
va_start(ap, e);
if ((Locate(A, ap, off)) <= 0)
{
exit(ERROR);
}
e = *(A.base + off);
return e;
}
为A指定位置赋值函数
Array Assign(Array A, ElemType e, ...) {
//A是n维数组,e是元素变量,随后是n个下标值
//若下标不超界,则将e值赋给所指定的A的元素
va_list ap;
int off = 0;
va_start(ap, e);
if (Locate(A, ap, off) <= 0)
{
exit(ERROR);
}
*(A.base + off) = e;
return A;
}
main函数调用
int main(void) {
int off = 0;
Array A = { NULL,0,NULL,NULL };
ElemType arrayB[4][3] = { {1,2,3},{4,5,6},{7,8,9},{10,11,12} };
int dim = 2, bounds = 4, constants = 3, e = 0;
A = InitArray(A, dim, bounds, constants);
for (int i = 0; i < bounds; i++)
{
for (int j = 0; j < constants; j++) {
Assign(A, arrayB[i][j], i, j);
printf("value=%d\n", Value(A, e, i, j));
}
}
printf("A.dim=%d\n", A.dim);
A = DestoryArray(A);
printf("A.base=%p\n", A.base);
}