这段代码是从老师那拷来的还没彻底理解。
- /*完成数组的初始化操作,
- * 从屏幕输入数组的维数和维界,
- * 初始化后返回成功或失败。
- * (可参照参考程序)*/
- #include <stdarg.h>
- #include <iostream.h>
- #include <malloc.h>
- #include <stdio.h>
- #include <conio.h>
- #define MAX_ARRAY_DIM 8
- #define ERROR 0
- #define OVERFLOW -1
- #define UNDERFLOW -2
- #define OK 1
- typedef int ElemType;
- typedef struct
- { ElemType *base;
- int dim;
- int *bounds;
- int *constants;
- }Array;
- //数据元素定位,ap为不定长参数
- int Locate(Array A,va_list ap,int &off)
- {
- int ind,i;
- 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;
- }
- //数组初始化
- int InitArray(Array &A,int dim,...)
- {
- int i,elemtotal=1;
- va_list ap;
- //初始化dim
- if(dim<1||dim>MAX_ARRAY_DIM) return (ERROR);
- A.dim=dim;
- //初始化bounds
- A.bounds=(int*)malloc(dim*sizeof(int));
- if(!A.bounds) return (OVERFLOW);
- va_start(ap,dim);
- for(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);
- //初始化基址base
- A.base=(ElemType*)malloc(elemtotal*sizeof(ElemType));
- if(!A.base) return(OVERFLOW);
- //初始化常数constant
- A.constants=(int*)malloc(dim*sizeof(int));
- if (!A.constants)
- return(OVERFLOW);
- A.constants[dim-1]=1;
- for(i=dim-2;i>=0;--i)
- {
- A.constants[i]=A.bounds[i+1]*A.constants[i+1];
- }
- return elemtotal;
- }
- void main()
- {
- Array A;
- int dim=2,r,i=0;
- int off=0;
- int Abound[MAX_ARRAY_DIM];
- int bound[MAX_ARRAY_DIM];
- printf("Locate.cpp/n==========/n/n");
- //从屏幕读取参数
- printf("Please input the dimentions of array you want to create: /n");
- scanf("%d",&dim);
- printf("please assign the length of each dimention: /n");
- for(i=0;i<dim;i++)
- {
- printf("Dimention%d.length= ",i+1);
- scanf("%d",&bound[i]);
- }
- if(r=InitArray(A,dim,bound[0],bound[1],bound[2],bound[3],bound[4],bound[5],bound[6],bound[7]))//初始化数组
- {
- cout<<"Success to Initialize a Array!"<<endl
- <<"Dimention= "<<dim<<endl<<"Total element is: "<<r<<endl<<endl;
- //从屏幕输入数据元素脚标
- cout<<"Please input the array subscripts of which you want to get its offset:"<<endl
- <<"Array[J1,J2,J3,...]"<<endl;
- for(i=0;i<dim;i++)
- {
- printf("J%d= ",i+1);
- scanf("%d",&Abound[i]);
- }
- va_list ap;
- ap=(char *)&Abound[0];
- r=Locate(A,ap,off);//调用定位函数
- if(r!=OVERFLOW)
- cout<<"Location in Array is:(Begin with Array[0,0,0...]) "<<off<<endl;
- else
- cout<<"OVERFLOW"<<endl;
- }
- }