Data Structure --- sequential storage representation of arrays in C Language (runable)
// Sequential storage representation of arrays // Yang Xin # include
# Include
# Include
# Include
# Define OK 1 # define ERROR 0 # define UNDERFLOW 2 # define MAX_ARRAY_DIM 8 typedef int Status; typedef int ElemType; typedef struct {ElemType * base; // array object int dim; // Array dimension int * bounds; // according to the following bound, it should be bounds, and the length of each dimension of the Array is int * constants; // base address of the Array image function constant} Array; // Array initialization Status InitArray (Array * A, int dim ,...) {int elemtotal = 1, I; va_list ap; if (dim <1 | dim> MAX_ARRAY_DIM) return ERROR; A-> dim = dim; A-> bounds = (int *) Malloc (dim * sizeof (int); if (! A-> bounds) return ERROR; va_start (ap, dim); for (I = 0; I
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); if (! A-> base) return ERROR; A-> constants = (int *) malloc (dim * sizeof (int); if (! A-> constants) return ERROR; A-> constants [dim-1] = 1; for (I = dim-2; I> = 0; -- I) a-> constants [I] = A-> bounds [I + 1] * A-> constants [I + 1]; return OK ;} // destroy the Array Status DestroyArray (Array * A) {free (A-> base); free (A-> bounds); free (A-> constants ); return OK;} // find the address Status Locate (Array A, va_list ap, int * off) {int ind, I; * off = 0; for (I = 0; I =. bounds [I]) return ERROR; * off + =. constants [I] * ind;} return OK;} // assign a value to the array AStatus Assign (Array * A, ElemType e ,...) {va_list ap; Status result; int I, j, k; int off; va_start (ap, e); if (result = Locate (* A, ap, & off )) <0) return result; * (A-> base + off) = e; va_end (ap); return OK ;} // assign the Value to the eStatus Value (Array A, ElemType * e,...) element specified in Array ,...) {int off; Status result; va_list ap; va_start (ap, e); if (result = Locate (A, ap, & off) <0) return result; * e = * (. base + off); va_start (ap, e); return OK;} int main () {int I, j, k; Array A; ElemType e;. dim = 3; InitArray (& A,. dim, 2, 2); printf ("this is an array of % d dimensions! \ N ", A. dim); printf (" size of each dimension of the array: \ n "); for (I = 0; I