#include #include /* int sum( int * arr, int N ) { int i; int theSum = 0; for( i = 0; i < N; i++ ) theSum += arr[ i ]; return theSum; } */ int sum( int *arr, int N ) { int *p = arr; int *endMarker = arr + N; int theSum = 0; while( p != endMarker ) theSum += *p++; return theSum; } /* * Fill in *N with # items read * Return arr of items allocated from memory heap */ int * readNumbers( int *N ) { int capacity = 5; int itemsRead = 0; int *arr = malloc( capacity * sizeof( int ) ); int x; printf( "Enter as many numbers, followed by ***\n" ); while( scanf( "%d", & x ) == 1 ) { if( itemsRead == capacity ) { capacity *= 2; arr = realloc( arr, capacity * sizeof( int ) ); if( arr == NULL ) return NULL; } arr[ itemsRead++ ] = x; } *N = itemsRead; return arr; } #define MAX_STRING 1023 /* * Fill in *N with # items read * Return arr of items allocated from memory heap */ char * * readStrings( int *N ) { char buffer[ MAX_STRING + 1 ]; int capacity = 3; int itemsRead = 0; char * *arr = malloc( capacity * sizeof( char * ) ); int x; printf( "Enter as many strings, followed by ***\n" ); while( scanf( "%1023s", buffer ) == 1 ) { if( strcmp( buffer, "***" ) == 0 ) break; if( itemsRead == capacity ) { capacity *= 2; arr = realloc( arr, capacity * sizeof( char * ) ); if( arr == NULL ) return NULL; } arr[ itemsRead++ ] = strdup( buffer ); } *N = itemsRead; return arr; } /* * Testing array expansion */ int main( ) { char * * arr; int theSum; int i; int N; arr = readStrings( &N ); for( i = 0; i < N; i++ ) printf( "String #%d: %s\n", i, arr[ i ] ); /* Cleanup mess */ for( i = 0; i < N; i++ ) free( arr[ i ] ); free( arr ); return 0; }