/* Phil Ottewell's STL Course - http://www.pottsoft.com/home/stl/stl.htmlx Example 1.1 © Phil Ottewell 1997 Purpose: Simple vector and sort demonstration using ANSI C */ /* ANSI C Headers */ #include #include #include /* Typedef array type in case we need to change it */ typedef int array_type; /* Function Prototypes */ int compare_values( const void *a, const void *b ); int *get_array_space( int num_items ); int main( int argc, char *argv[] ) { int i; int nitems = 0; array_type ival; array_type *v; fprintf(stdout,"Enter integers, after each, Z to finish:\n"); while( EOF != fscanf( stdin, "%d", &ival) ) { v = get_array_space( nitems+1 ); v[nitems] = ival; fprintf( stdout, "%6d: %d\n", nitems, v[nitems] ); ++nitems; } if ( nitems ) { qsort( v, nitems, sizeof(array_type), compare_values ); for ( i = 0; i < nitems; ++i ) fprintf( stdout, "%d ", v[i] ); fprintf( stdout, "\n" ); } return( EXIT_SUCCESS ); } /*---- Comparison func returns: -ve if a < b, 0 if a == b, +ve if a > b ----*/ int compare_values( const void *a, const void *b ) { const array_type *first, *second; /* End of declarations ... */ first = (array_type *)a; second = (array_type *)b; return( *first - *second ); } /*---- Allocate space: n == 0 return pointer, n > 0 expand/realloc if needed -*/ int *get_array_space( int n ) { const int extra_space = 2; array_type *new_space_ptr; static array_type *array_space_ptr; static int mxitm; /* End of declarations ... */ if ( n > 0 ) { if ( n > mxitm ) { n += extra_space; if ( array_space_ptr ) { new_space_ptr = realloc(array_space_ptr,sizeof(array_type)*n); if ( new_space_ptr ) { /* Successfully expanded the space */ array_space_ptr = new_space_ptr; /* Clear new storage space */ memset( &array_space_ptr[mxitm], 0, sizeof(array_type)*(n-mxitm) ); } else { /* Couldn't allocate the space */ exit( EXIT_FAILURE ); } } else { array_space_ptr = (array_type *)calloc( n, sizeof(array_type) ); if ( !array_space_ptr ) { /* Couldn't allocate the space */ exit( EXIT_FAILURE ); } } mxitm = n; } } return( array_space_ptr ); }