You could consider using qsort to sort the array of pointers to strings, then using bsearch to search the array.
Use the same compare function for both calls. It's pretty efficient if you do more searching than sorting.
Both functions are in stdlib.h
An example using ints as the data type
Code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define A_SIZE 50
int compare ( const void *a, const void *b ) {
const int *pa = a;
const int *pb = b;
if ( *pa < *pb ) return -1;
if ( *pa > *pb ) return +1;
return 0;
}
void print_arr ( int *arr ) {
int i;
for ( i = 0 ; i < A_SIZE ; i++ ) {
printf( "%2d ", arr[i] );
if ( (i+1) % 10 == 0 ) printf( "\n" );
}
printf( "\n" );
}
int main ( ) {
int test[A_SIZE];
int i;
int key, *result;
// get some test data
srand( time(NULL) );
for ( i = 0 ; i < A_SIZE ; i++ ) {
test[i] = rand() % 100;
}
print_arr( test );
// sort the array using some compare function
qsort( test, A_SIZE, sizeof(test[0]), compare );
print_arr( test );
// search the array,
// using a key of the same type,
// and the same compare function
key = rand() % 100;
result = bsearch( &key, test, A_SIZE, sizeof(test[0]), compare );
if ( result ) {
printf( "Found %d\n", *result );
} else {
printf( "Not found %d\n", key );
}
return 0;
}