#include <stdio.h> // for printf
#include <stdlib.h> // for qsort, malloc, free
#include <string.h> // for strcmp
/* ------------------------------------------------------------
Example: Sorting an array of structs that contain nested structs
------------------------------------------------------------ */
/* A nested struct representing an address */
struct Address {
char city[64];
int zip;
};
/* A struct representing a person, containing a nested Address */
struct Person {
char name[64];
int age;
struct Address address;
};
/* ------------------------------------------------------------
Comparison function for qsort:
Sort by city name first, then by zip code, then by age.
------------------------------------------------------------ */
int comparePersons(const void *a, const void *b) {
const struct Person *pa = (const struct Person *)a;
const struct Person *pb = (const struct Person *)b;
/* Compare by city */
int cityCmp = strcmp(pa->address.city, pb->address.city);
if (cityCmp != 0)
return cityCmp;
/* If cities are equal, compare by zip */
if (pa->address.zip != pb->address.zip)
return pa->address.zip - pb->address.zip;
/* If zip codes are equal, compare by age */
return pa->age - pb->age;
}
/* ------------------------------------------------------------
Helper function to print the list
------------------------------------------------------------ */
void printPersons(const struct Person *people, size_t count) {
for (size_t i = 0; i < count; ++i) {
printf("%s | age: %d | city: %s | zip: %d\n",
people[i].name,
people[i].age,
people[i].address.city,
people[i].address.zip);
}
}
/* ------------------------------------------------------------
Main program
------------------------------------------------------------ */
int main(void) {
/* Create a sample list of people */
struct Person people[] = {
{"Alice", 30, {"San Francisco", 42100}},
{"Bob", 40, {"Austin", 32000}},
{"Carol", 35, {"New York City", 42000}},
{"Dave", 25, {"Austin", 32000}},
{"Eve", 28, {"New York City", 61000}}
};
size_t count = sizeof(people) / sizeof(people[0]);
/* Sort using qsort and our custom comparison function */
qsort(people, count, sizeof(struct Person), comparePersons);
/* Print the sorted result */
printPersons(people, count);
return 0;
}
/*
run:
Dave | age: 25 | city: Austin | zip: 32000
Bob | age: 40 | city: Austin | zip: 32000
Carol | age: 35 | city: New York City | zip: 42000
Eve | age: 28 | city: New York City | zip: 61000
Alice | age: 30 | city: San Francisco | zip: 42100
*/