头文件
#ifndef ARRAYHEAD_H_INCLUDED
#define ARRAYHEAD_H_INCLUDED
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_DIM 8
typedef struct
{
int* base ;
int dim ;
int* bounds ;
int* constants ;
} Array ;
int InitArray( Array* A , int dim , ... ) ;
int DestroyArray( Array* A ) ;
int LocateArray( Array* A , int* off , va_list Loc_dim ) ;
int GetValue( Array* A , int* elem , ... ) ;
int SetValue( Array* A , int* elem , ... ) ;
#endif // ARRAYHEAD_H_INCLUDED
函数实现
#include "arrayhead.h"
int InitArray( Array* A , int dim , ... )
{
if( dim < 0 || dim > MAX_DIM )
{
printf( "DIM ERROR!\n" ) ;
exit( 1 ) ;
}
A->dim = dim ;
A->bounds = ( int* )malloc( dim * sizeof( int ) ) ;
if( !A->bounds )
{
printf( "BOUNDS ERROR!\n" ) ;
exit( 1 ) ;
}
int TotalElem = 1 ;
va_list len_dim ;
va_start( len_dim , dim ) ;
int i ;
for( i = 0 ; i < dim ; i++ )
{
A->bounds[i] = va_arg( len_dim , int ) ;
if( A->bounds[i] <= 0 )
{
printf( "BOUNDS ILLEGAL!\n" ) ;
exit( 1 ) ;
}
TotalElem *= A->bounds[i] ;
}
va_end( len_dim ) ;
A->base = ( int* )malloc( TotalElem * sizeof( int ) ) ;
if( !A->base )
{
printf( "BASE ERROR!\n" ) ;
exit( 1 ) ;
}
A->constants = ( int* )malloc( dim * sizeof( int ) ) ;
if( !A->constants )
{
printf( "CONSTANTS ERROR!\n" ) ;
exit( 1 ) ;
}
A->constants[dim -1] = 1 * sizeof( int ) ;
for( i = dim - 2 ; i >= 0 ; i-- )
{
A->constants[i] = A->constants[i + 1] * A->bounds[i + 1] ;
}
return 0 ;
}
int DestroyArray( Array* A )
{
if( !A->base )
{
exit( 1 ) ;
}
free( A->base ) ;
A->base = NULL ;
if( !A->bounds )
{
exit( 1 ) ;
}
free( A->bounds ) ;
A->bounds = NULL ;
if( !A->constants )
{
exit( 1 ) ;
}
free( A->constants ) ;
A->constants = NULL ;
A->dim = 0 ;
return 0 ;
}
int LocateArray( Array* A , int* off , va_list Loc_dim )
{
*off = 0 ;
int i ;
int posdim = -1 ;
for( i = 0 ; i < A->dim ; i++ )
{
posdim = va_arg( Loc_dim , int ) ;
if( posdim < 0 || posdim >= A->bounds[i] )
{
printf( "LOCATION ERROR!\n" ) ;
exit( 1 ) ;
}
off = off + posdim * A->constants[i] ;
}
return 0 ;
}
int GetValue( Array* A , int* elem , ... )
{
va_list Off_Loc ;
va_start( Off_Loc , elem ) ;
int off = 0 ;
LocateArray( A , &off , Off_Loc ) ;
va_end( Off_Loc ) ;
*elem = *( A->base + off ) ;
return 0 ;
}
int SetValue( Array* A , int* elem , ... )
{
va_list Off_Loc ;
va_start( Off_Loc , elem ) ;
int off = 0 ;
LocateArray( A , &off , Off_Loc ) ;
va_end( Off_Loc ) ;
*( A->base + off ) = *elem ;
return 0 ;
}
main函数测试
#include "arrayhead.h"
int main()
{
Array A ;
int elem = 20 ;
int e = 0 ;
InitArray( &A , 3 , 5 , 6 , 7 , 8 ) ;
printf( "%d\n" , A.dim ) ;
SetValue( &A , &elem , 4 , 5 , 6 ) ;
GetValue( &A , &e , 4 , 5 , 6 ) ;
printf( "%d\n" , e ) ;
return 0 ;
}
总结:因为数组主要是存取和修改的操作,而没有增删的操作,所以使用顺序结构存储。对多维数组是一个随机存取的结构。