Your qsort approach is good, but you need to define a different sorting function for use in the 4th parameter.
The best way of doing this is to collect all the sort functions into an array, then present the user with a choice of which sort function to use. The user's choice simply indexes this array.
Code:
#include <stdio.h>
#include <stdlib.h>
#define NUM_ENTRIES(x) (sizeof(x)/sizeof(x[0]))
typedef struct person {
char f_name[50];
char l_name[50];
int age;
char state[50];
} p_st;
/* one of these for each type of sort */
int sort_f_name ( const void *a, const void *b ) {
const p_st *pa = a;
const p_st *pb = b;
return strcmp( pa->f_name, pb->f_name );
}
int sort_l_name ( const void *a, const void *b ) {
const p_st *pa = a;
const p_st *pb = b;
return strcmp( pa->l_name, pb->l_name );
}
typedef int (*sort_fn)(const void*, const void *);
sort_fn sort_fns[] = {
sort_f_name,
sort_l_name,
/* Add more here */
};
void print_arr ( p_st *arr, int n ) {
int i;
for ( i = 0 ; i < n ; i++ ) {
printf( "%s %s %d %s\n",
arr[i].f_name, arr[i].l_name, arr[i].age, arr[i].state );
}
}
int main ( ) {
p_st persons[] = {
{ "charlie", "walker", 22, "iowa" },
{ "rick", "davis", 31, "virginia" },
{ "sarah", "campo", 18, "utah" },
};
printf( "Original\n" );
print_arr( persons, NUM_ENTRIES(persons) );
printf( "\nFirst name\n" );
qsort( persons, NUM_ENTRIES(persons), sizeof(p_st), sort_fns[0] );
print_arr( persons, NUM_ENTRIES(persons) );
printf( "\nLast name\n" );
qsort( persons, NUM_ENTRIES(persons), sizeof(p_st), sort_fns[1] );
print_arr( persons, NUM_ENTRIES(persons) );
return 0;
}
Enjoy!!!