>I have searched around on google but can't find anything of much help.
That's a bit odd. Sorting an array of structures based on a single field is a common question and has a common answer:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH(x) (sizeof x / sizeof *x)
struct test {
char name[40];
int age;
};
int cmp_name(const void *a, const void *b)
{
const struct test *sa = a;
const struct test *sb = b;
return strcmp(sa->name, sb->name);
}
int cmp_age(const void *a, const void *b)
{
const struct test *sa = a;
const struct test *sb = b;
if (sa->age < sb->age)
return -1;
else if (sa->age > sb->age)
return +1;
else
return 0;
}
int main(void)
{
struct test my_test[] = {
{"Julienne", 21}, /* I wish ;) */
{"Tom", 29},
{"Generic Guy", 40},
{"Generic Girl", 40},
{"Other People", 33},
{"Too lazy to think up another", 13},
};
int i;
qsort(my_test, LENGTH(my_test), sizeof my_test[0], cmp_name);
for (i = 0; i < LENGTH(my_test); i++)
printf("%s -- %d\n", my_test[i].name, my_test[i].age);
printf("\n");
qsort(my_test, LENGTH(my_test), sizeof my_test[0], cmp_age);
for (i = 0; i < LENGTH(my_test); i++)
printf("%s -- %d\n", my_test[i].name, my_test[i].age);
printf("\n");
return 0;
}