What are Sort Structures by Multiple Keys- Best Embedded C Programming Course

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Structure and Union

Sort Structures by Multiple Keys

Nested date structures, a menu of comparison functions and the standard qsort call: sort structures by multiple keys in C the clean way.

Real tables are rarely sorted one way. A firmware catalogue might be listed by name, by build date, by ship date or by image size, depending on who is looking. This lecture shows how to sort structures by multiple keys in C without writing four copies of the sorting loop. We use nested structures for dates, comparison functions, and a table of function pointers. It is the most practical lesson so far in our free C programming course, and a must-know topic in embedded C programming and every good free C tutorial.

What You Will Learn

  • How to nest one structure inside another and reach inner members with chained dots
  • How to compare two dates correctly: year, then month, then day
  • How to write comparison functions in the shape qsort expects
  • How to pick the sort key at run time using a table of function pointers
  • Why subtracting two integers is a dangerous way to compare them

Prerequisites

Complete the previous lecture on sorting arrays of structures. You also need the basics of function pointers and the const void * pointer type.

Nested Structures for Dates

A date has three parts that belong together, so it earns its own structure. The firmware record then contains two dates: when the image was built and when it shipped. Access goes through two dots, for example fw.built.year. A nested structure is stored inline, not through a pointer, so the whole record is still one contiguous block.

Layout of one firmware record
name[16]
builtdaymonthyear
shippeddaymonthyear
size_kb

Comparing Dates Correctly

Dates cannot be compared member by member in any order. The year has the highest weight, then the month, then the day. A comparison function therefore checks the year first and only looks at the month when the years are equal, and so on. It returns a negative number, zero or a positive number, the same contract used by strcmp.

Return valueMeaning
NegativeThe first item should come before the second
ZeroBoth items are equal for this key
PositiveThe first item should come after the second

Comparators to Sort Structures by Multiple Keys in C

The standard qsort function sorts any array. It knows nothing about your structure, so it asks you to supply a comparator taking two const void * pointers to elements. Inside, you cast them back to your structure type. One comparator per key is all you need.

One sorting engine, many keys
sort_key table
“name” → cmp_name“build date” → cmp_built
“ship date” → cmp_shipped“image size” → cmp_size
qsort(work, N, sizeof work[0], chosen_cmp)

Complete Program: Sort Structures by Multiple Keys in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 5

struct date { int day, month, year; };

struct firmware {
    char        name[16];
    struct date built;
    struct date shipped;
    int         size_kb;
};

static int datecmp(struct date a, struct date b)
{
    if (a.year  != b.year)  return a.year  < b.year  ? -1 : 1;
    if (a.month != b.month) return a.month < b.month ? -1 : 1;
    if (a.day   != b.day)   return a.day   < b.day   ? -1 : 1;
    return 0;
}

static int cmp_name(const void *x, const void *y)
{
    const struct firmware *a = x, *b = y;
    return strcmp(a->name, b->name);
}
static int cmp_built(const void *x, const void *y)
{
    const struct firmware *a = x, *b = y;
    return datecmp(a->built, b->built);
}
static int cmp_shipped(const void *x, const void *y)
{
    const struct firmware *a = x, *b = y;
    return datecmp(a->shipped, b->shipped);
}
static int cmp_size(const void *x, const void *y)
{
    const struct firmware *a = x, *b = y;
    return (a->size_kb > b->size_kb) - (a->size_kb < b->size_kb);
}

struct sort_key {
    const char *label;
    int (*cmp)(const void *, const void *);
};

static void print_table(const struct firmware *f, int n)
{
    for (int i = 0; i < n; i++)
        printf("  %-8s built %02d/%02d/%d  shipped %02d/%02d/%d  %4d KB\n",
               f[i].name,
               f[i].built.day, f[i].built.month, f[i].built.year,
               f[i].shipped.day, f[i].shipped.month, f[i].shipped.year,
               f[i].size_kb);
}

int main(void)
{
    const struct firmware base[N] = {
        { "bootldr", {12, 3, 2025}, {20, 3, 2025},  64 },
        { "wifi",    { 5, 9, 2024}, {10, 1, 2025}, 512 },
        { "audio",   {30, 1, 2025}, { 2, 2, 2025}, 256 },
        { "ble",     {18, 7, 2024}, {25, 8, 2024}, 128 },
        { "motor",   { 9, 11, 2024}, {15, 12, 2024}, 96 }
    };
    const struct sort_key keys[] = {
        { "name",         cmp_name    },
        { "build date",   cmp_built   },
        { "ship date",    cmp_shipped },
        { "image size",   cmp_size    }
    };

    for (size_t k = 0; k < sizeof keys / sizeof keys[0]; k++) {
        struct firmware work[N];
        memcpy(work, base, sizeof work);
        qsort(work, N, sizeof work[0], keys[k].cmp);
        printf("sorted by %s:\n", keys[k].label);
        print_table(work, N);
        printf("\n");
    }
    return 0;
}

Build and Run

$ gcc -std=c17 -Wall -Wextra -o ex24 ex24.c
$ ./ex24
sorted by name:
  audio    built 30/01/2025  shipped 02/02/2025   256 KB
  ble      built 18/07/2024  shipped 25/08/2024   128 KB
  bootldr  built 12/03/2025  shipped 20/03/2025    64 KB
  motor    built 09/11/2024  shipped 15/12/2024    96 KB
  wifi     built 05/09/2024  shipped 10/01/2025   512 KB

sorted by build date:
  ble      built 18/07/2024  shipped 25/08/2024   128 KB
  wifi     built 05/09/2024  shipped 10/01/2025   512 KB
  motor    built 09/11/2024  shipped 15/12/2024    96 KB
  audio    built 30/01/2025  shipped 02/02/2025   256 KB
  bootldr  built 12/03/2025  shipped 20/03/2025    64 KB

sorted by ship date:
  ble      built 18/07/2024  shipped 25/08/2024   128 KB
  motor    built 09/11/2024  shipped 15/12/2024    96 KB
  wifi     built 05/09/2024  shipped 10/01/2025   512 KB
  audio    built 30/01/2025  shipped 02/02/2025   256 KB
  bootldr  built 12/03/2025  shipped 20/03/2025    64 KB

sorted by image size:
  bootldr  built 12/03/2025  shipped 20/03/2025    64 KB
  motor    built 09/11/2024  shipped 15/12/2024    96 KB
  ble      built 18/07/2024  shipped 25/08/2024   128 KB
  audio    built 30/01/2025  shipped 02/02/2025   256 KB
  wifi     built 05/09/2024  shipped 10/01/2025   512 KB

Why the Build and Ship Orders Differ

Look at the “wifi” row. It was built in September 2024 but shipped in January 2025, so it sits third in ship order while second in build order. This is the point of sorting by several keys: the same data tells different stories depending on the key you choose. Each sort starts from a fresh copy made with memcpy, so one ordering never disturbs the next.

Why Not Just Subtract?

Never write return a - b; for integers. When the values are far apart, for example a very large positive and a negative number, the subtraction overflows and the sign of the result flips, so the sort order becomes wrong. Signed overflow is also undefined behaviour. The expression (a > b) - (a < b) yields exactly -1, 0 or 1 and can never overflow.

Combining Keys in One Comparator

So far each sort used a single key. Sometimes you need a primary and a secondary key, for example “sort by ship date, and among equal dates by name”. To sort structures by multiple keys in C in a single pass, write one comparator that checks the primary key first and falls through to the secondary key only when the primary comparison returns zero. The pattern is: compute the result for key one, return it if it is non-zero, then try key two, and so on. The next lecture builds a three-level comparator like this and shows why every record should end up distinguishable.

Real-World Use Cases

  • Listing installed firmware images by version or by date in a bootloader menu
  • Sorting log files by modification time in an embedded Linux device
  • Ordering employee-style records in a payroll or access-control terminal
  • Ranking sensor nodes by battery level or last-seen time in a gateway

Common Mistakes and Troubleshooting

  • Wrong element size: passing sizeof(struct firmware *) instead of the structure size scrambles the table
  • Casting the wrong way: the comparator receives pointers to elements, not elements; with an array of pointers you receive pointers to pointers
  • Date compared as a single integer: comparing only day makes 30 January look later than 12 March
  • Dropping const: casting away const in a comparator invites accidental writes during a sort

Best Practices, Performance and Security

Habits worth keeping

  • Keep comparators tiny, pure and free of side effects
  • Store dates as year, month and day, or as one packed value such as yyyymmdd, to make comparison cheap
  • qsort costs about n log n comparisons; on a deeply constrained MCU check its code size first
  • Validate every date that comes from a user or a network before sorting on it

Summary: Sort Structures by Multiple Keys in C

  • Nested structures keep related members together and are reached with chained dots
  • A date comparison checks year, then month, then day
  • One comparator per key plus qsort replaces many hand-written sorting loops
  • A table of function pointers lets the program pick the key at run time
  • Use (a > b) - (a < b), never subtraction, to compare integers

You can now sort structures by multiple keys in C using nested date structures, one comparator per key and a table of function pointers. That design scales to any number of keys, because to sort structures by multiple keys in C you only add one more comparator and one more table row, never another sorting loop.

Frequently Asked Questions

What does qsort need from me?

The array, the element count, the element size and a comparison function that returns negative, zero or positive.

Why do comparators take const void pointers?

So that one sorting function can work with any element type. You cast the pointers back inside the comparator.

Can I compare two dates with a single subtraction?

Not safely. Compare year, then month, then day, or pack the date into one number like yyyymmdd first.

Is qsort stable?

The standard does not promise it. Equal elements may swap places, so add a tie-breaker key when order matters, as the next lecture shows.

How do I sort in descending order?

Swap the two arguments in the final comparison, or negate the returned sign.

Free C Tutorial for Embedded Developers

Finish the structure chapter in our free embedded C course and test yourself in the final lab.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →