#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void swap(char *args1, char *args2) {
char tmp[40];
strcpy( tmp, args1 );
strcpy( args1, args2 );
strcpy( args2, tmp );
}

void sort(char ** args, const int start, const int end) {
char *pivot = args[end];
int i = start-1, j = start;
while( j < end ) {
int cmp = strcmp( pivot, args[j] );
if( cmp > 0 )
swap( args[++i], args[j] );
j++;
}
swap( args[++i], pivot );
if( start + 1 < i )
sort( args, start, i - 1 );
if( end - 1 > i )
sort( args, i + 1, end );
}

void wsort(char ** args, const int count) {
sort( args, 0, count - 1 );
}

int main() {
const int length = 40;
const int increment = 20;
int size = 20;
printf( "Insert words consisting of up to %d characters. One word for each line.\n", length );
char **buffer = calloc( size, sizeof(char *) );
if( !buffer )
return 1;
int i = 0;
for(;;) {
buffer[i] = calloc( length, sizeof(char) );
if( !buffer[i] )
return 2;
if( !fgets( buffer[i], length, stdin ) )
break;
i++;
if( i == size ) {
buffer = realloc( buffer, (size+=increment) * length * sizeof(char *) );
if( !buffer )
return 3;
}
}
printf( "%d items will be sorted now...\n", i );
wsort( buffer, i );
printf( "Sorting complete. Here is the resulting list:\n" );
for( int j = 0; j < i; j++ )
printf( "%s", buffer[j] );
}