数组的底层实现

#include <iostream>
#include <stdlib.h>
#include <string.h>
#define max 8
#define Elemtype int
using namespace std;

typedef struct {
	Elemtype *base;
	int *bounds;
	int dim;//数组维数 
}Array;
int n,num,bound[9],i=0;

int Loc(int d,int *bound,int *pos)
{
	int num=0,i;
	for (i=0;i<d-1;i++) {
		num+=pos[i]*bound[i];
	}
	return num+pos[i];
}

int sum(Array &a)
{
	int sum=1;
	for (int i=0;i<a.dim;i++) {
		sum*=a.bounds[i];
	}
	return sum;
}
int InitArray(Array &a,int d,int *bound)
{
	a.bounds=(int *)malloc(sizeof(int)*d);
	if (a.bounds==NULL) {
		cout<<"Allocation failure."<<endl;
		return -1;
	}
	for (int i=0;i<d;i++) {
		a.bounds[i]=bound[i];
	}
	a.dim=d;
	int s=sum(a);
	a.base=(Elemtype *)malloc(sizeof(Elemtype)*s);
	if (a.base==NULL) {
		cout<<"Allocation failure."<<endl;
		free(a.bounds);
		a.bounds=NULL;
		a.dim=0;
		return -1;
	}
	memset(a.base,0,sizeof(Elemtype)*s);
	cout<<"Initial successfully!"<<endl;
	return 0;
}

int DestroyArray(Array &a)
{
	if (a.base==NULL) {
		cout<<"The array is empty."<<endl;
		return -1;
	}
	free(a.base);
	a.base=NULL;
	free(a.bounds);
	a.bounds=NULL;
	a.dim=0;
	cout<<"Successfully destruction."<<endl;
	return 0;
}

int value(Array &a,Elemtype e,int *bound)
{
	int s=sum(a);
	int p=Loc(a.dim,a.bounds,bound);
	if (p>=s) {
		cout<<"Position is illegal."<<endl;
		return -1;
	}
	*(a.base+p)=e;
	cout<<"Set up success."<<endl;
	return 0;
}

int Print(Array &a)
{
	int s=sum(a);
	for (int i=0;i<s;i++) {
		cout<<*(a.base+i)<<" ";
	}
	cout<<endl;
	return 0;
}

int main()
{
	cout<<"Please enter what do you want to do. Enter 0 will exit."<<endl
	<<"1.Initial Array."<<endl
	<<"2.Destroy Array."<<endl
	<<"3.Sets the value of the array element."<<endl
	<<"4.Print all elements of the array."<<endl;
	Array array;
	array.base=NULL;
	array.bounds=NULL;
	array.dim=0;
	Elemtype e;
	int num;
	int Bound[max];
	while (cin>>n&&n) {
		switch (n) {
			case 1:
				cout<<"How many dim do you want to create?"<<endl;
				cin>>num;
				cout<<"Please enter the every bound of dim."<<endl;
				for (int i=0;i<num;i++) {
					cin>>Bound[i];
				}
				InitArray(array,num,Bound);
				break;
			case 2:
				DestroyArray(array);
				break;
			case 3:
				if (array.base==NULL) {
					cout<<"Array is empty."<<endl;
				}
				cout<<"Where do you want to set? Please enter "<<array.dim<<" number."<<endl;
				for (int i=0;i<array.dim;i++) {
					cin>>Bound[i];
				}
				cout<<"Please enter the number you want to set."<<endl;
				cin>>e;
				value(array,e,Bound);
				break;
			case 4:
				Print(array);
		}
	}
	return 0;
}
/*
test case:
1
2
5 6
3
0 1
9
4
*/
原文地址:https://www.cnblogs.com/xyqxyq/p/10211365.html