here is an example of qsort with array of structures, copy and run on your compiler...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[20];
char number[5];
} COMPANY;
int compare1 (const void *a, const void *b);
int compare2 (const void *a, const void *b);
void main ()
{
COMPANY customer[5]={
{"GREENS PAINTS", "2812"},
{"ALBANY STORES", "5612"},
{"STATIC DOORS", "4587"},
{"DIBBLES GARDENS", "9587"},
{"STATION GRADE", "5487"}
};
COMPANY *str_ptr1, *str_ptr2;
int i = 0;
if((str_ptr1 =(COMPANY *) malloc (sizeof(COMPANY) * 5)) ==NULL) {
printf("\nUnable to allocate memory");
exit (1);
}
printf("Before sort\n");
str_ptr2 = str_ptr1;
while(i < 5) {
printf("\n%20s %5s", customer[i].name, customer[i].number);
strcpy(str_ptr2->name, customer[i].name);
strcpy(str_ptr2->number, customer[i].number);
str_ptr2++; i++;
}
str_ptr2 = str_ptr1;
qsort(str_ptr2, 5, sizeof(COMPANY), compare1);
printf("\n\nAfter first sort - by name\n");
i = 0;
str_ptr2 = str_ptr1;
while(i < 5) {
strcpy(customer[i].name, str_ptr2->name);
strcpy(customer[i].number, str_ptr2->number);
printf("\n%20s %5s", customer[i].name, customer[i].number);
str_ptr2++;
i++;
}
str_ptr2 = str_ptr1;
qsort(str_ptr2, 5, sizeof(COMPANY), compare2);
printf("\n\nAfter second sort - by number\n");
i = 0;
str_ptr2 = str_ptr1;
while(i < 5) {
strcpy(customer[i].name, str_ptr2->name);
strcpy(customer[i].number, str_ptr2->number);
printf("\n%20s %5s", customer[i].name, customer[i].number);
str_ptr2++;
i++;
}
str_ptr2 = str_ptr1;
free(str_ptr1);
printf("\nHit Return to quit");
getchar();
} /*main*/
int compare1 (const void *a, const void *b)
{
return ( strcmp(((COMPANY*)a)->name, ((COMPANY*)b)->name));
}
int compare2 (const void *a, const void *b)
{
return ( strcmp(((COMPANY*)a)->number, ((COMPANY*)b)->number));
}