What are Sorting Arrays of Structures- Free 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

Sorting Arrays of Structures

Sort an array of structures in C by swapping whole records, then do it again with pointers and see how many bytes you save in embedded C programming.

To sort an array of structures in C you compare one member, called the key, and move entire records into order. That sounds simple until the records are large. In this lecture of our free C programming course we sort a firmware event log two ways: by swapping full structures, and by swapping pointers to them. The numbers show why embedded C programming developers care. It is a hands-on free C tutorial you can compile and measure yourself.

What You Will Learn

  • How to choose a sort key inside a structure
  • How to swap two whole structures using a temporary variable
  • How an array of pointers lets you sort without moving data
  • How to count and compare the bytes each method moves
  • When the pointer method is the right choice on small microcontrollers

Prerequisites

You should know how to pass an array of structures to a function, how structure assignment works, and how bubble sort compares neighbours.

Pick the Key, Then Sort an Array of Structures in C

A structure has many members, but sorting needs only one rule at a time. Our log record has a timestamp, a severity level and a message. We want entries in time order, so ts is the key. The comparison a[j].ts > a[j + 1].ts decides whether two neighbours are out of order, and everything else in the record simply travels along.

Sort an Array of Structures in C: Swap Whole Records

C allows assigning one structure to another, so a swap is three assignments through a temporary of the same type. The cost is that every assignment copies every byte of the record, including the 48-byte message buffer.

Swapping whole structures
a[j]56 bytes → tmp
a[j+1]56 bytes → a[j]
tmp56 bytes → a[j+1]
Total moved per swap: 168 bytes

Sort an Array of Structures in C Through an Index of Pointers

Instead of moving records, build a second array that holds the address of each record. Sorting that array only swaps 8-byte pointers. The original table stays exactly as it was, which is a bonus when other code holds addresses into it or when the table lives in flash and cannot be rewritten at all.

Sorting through an index
logs[0] ts=400logs[1] ts=100logs[2] ts=300data never moves
idx before: →0 →1 →2
idx after: →1 →2 →0 (ts order 100, 300, 400)

Complete Program: Compare Both Methods

#include <stdio.h>
#include <stddef.h>

#define N 6

struct log_entry {
    unsigned      ts;
    unsigned char level;
    char          msg[48];
};

static unsigned swaps_copy, swaps_ptr;

/* Version 1: swap whole structures */
static void sort_copy(struct log_entry a[], int n)
{
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - 1 - i; j++)
            if (a[j].ts > a[j + 1].ts) {
                struct log_entry tmp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = tmp;
                swaps_copy++;
            }
}

/* Version 2: swap pointers, structures stay where they are */
static void sort_ptr(struct log_entry *p[], int n)
{
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - 1 - i; j++)
            if (p[j]->ts > p[j + 1]->ts) {
                struct log_entry *tmp = p[j];
                p[j] = p[j + 1];
                p[j + 1] = tmp;
                swaps_ptr++;
            }
}

int main(void)
{
    struct log_entry logs[N] = {
        { 400, 2, "uart rx overrun" },
        { 100, 0, "boot ok" },
        { 300, 1, "i2c retry" },
        { 600, 3, "watchdog kick missed" },
        { 200, 0, "adc calibrated" },
        { 500, 2, "spi timeout" }
    };
    struct log_entry copy[N];
    struct log_entry *idx[N];

    for (int i = 0; i < N; i++) {
        copy[i] = logs[i];
        idx[i] = &logs[i];
    }

    printf("sizeof(struct log_entry) = %zu, sizeof(pointer) = %zu\n",
           sizeof(struct log_entry), sizeof(idx[0]));

    sort_copy(copy, N);
    sort_ptr(idx, N);

    printf("\nsorted through the pointer array:\n");
    for (int i = 0; i < N; i++)
        printf("  %3u  L%u  %s\n", idx[i]->ts, idx[i]->level, idx[i]->msg);

    printf("\noriginal array first element is still ts=%u\n", logs[0].ts);
    printf("copy-sort swaps=%u (about %zu bytes moved)\n",
           swaps_copy, swaps_copy * 3 * sizeof(struct log_entry));
    printf("ptr-sort  swaps=%u (about %zu bytes moved)\n",
           swaps_ptr, swaps_ptr * 3 * sizeof(idx[0]));
    return 0;
}

Build and Run

$ gcc -std=c17 -Wall -Wextra -o ex23 ex23.c
$ ./ex23
sizeof(struct log_entry) = 56, sizeof(pointer) = 8

sorted through the pointer array:
  100  L0  boot ok
  200  L0  adc calibrated
  300  L1  i2c retry
  400  L2  uart rx overrun
  500  L2  spi timeout
  600  L3  watchdog kick missed

original array first element is still ts=400
copy-sort swaps=6 (about 1008 bytes moved)
ptr-sort  swaps=6 (about 144 bytes moved)

What the Numbers Tell You

Both methods perform exactly six swaps because they run the same algorithm on the same data. The difference is the price of each swap: 168 bytes against 24. Over the whole sort, 1008 bytes moved against 144, a factor of seven. The structure is 56 bytes rather than 53 because the compiler pads it to a multiple of its 4-byte alignment. With six records this is trivial; with five hundred records on a 48 MHz core, it decides whether the sort finishes inside your time budget.

QuestionSwap structuresSort pointers
Bytes moved per swap3 × record size3 × pointer size
Original table changes?YesNo
Extra memoryOne temporary recordOne pointer per record
Access after sortingDirect, a[i].tsOne extra hop, p[i]->ts
Best forSmall records, data you want physically orderedLarge records, read-only tables, several orderings at once

Real-World Use Cases

  • Ordering a ring-buffer snapshot of events before sending it over UART
  • Keeping one record table but several views: by time, by severity, by source
  • Ranking scan results in a Bluetooth or Wi-Fi scanner by signal strength
  • Sorting flash-resident tables that cannot be modified at runtime

Choosing the Sort Algorithm

The lecture uses bubble sort because it is short enough to read at a glance, and because every swap is visible, which makes the byte counts easy to explain. It performs roughly n squared comparisons, so it is fine for a table of ten or twenty entries but wasteful for hundreds. Insertion sort is a good upgrade for small, nearly sorted tables such as a log that is already mostly in time order. When the table grows, call the standard library routine and supply a comparator, which is the subject of the next lecture.

Whichever algorithm you pick, the decision between moving records and moving pointers stays the same. That decision is the heart of how to sort an array of structures in C efficiently, and you can apply it unchanged to insertion sort, selection sort or qsort. Measure with realistic record sizes before you decide, because a four-byte record gains nothing from an index.

Common Mistakes and Troubleshooting

Comparing the wrong thing. Writing if (a[j] > a[j + 1]) does not compile, because structures cannot be compared with relational operators. Always compare a specific member.

  • Using == on structures: not allowed either; compare member by member
  • Reading the wrong array: after a pointer sort the original array is unchanged, so print through idx
  • Loop bounds: the inner loop must stop at n - 1 - i or it reads past the end
  • Dangling pointers: if the record array goes out of scope, the index points at garbage

Best Practices, Performance and Security

Guidelines

  • Sort pointers when records are bigger than a few machine words
  • Bubble sort is fine for tens of records; use qsort for more (covered next)
  • Never trust a record count received from outside; clamp it to the array size first
  • Keep the original table const when you only need an ordered view

Summary and Key Takeaways

  • To sort an array of structures in C, pick one member as the key and compare only that
  • Whole-structure swapping is easy to write but moves a lot of data
  • An index array of pointers sorts the same data while leaving it in place
  • Padding makes sizeof larger than the sum of the members

You can now sort an array of structures in C by copying records or by reordering pointers, and you know how to measure the cost of each choice. Remember that to sort an array of structures in C well, you should always start from the record size, not from habit.

Frequently Asked Questions

Can I assign one structure to another in C?

Yes, assignment copies every member. You cannot compare whole structures with == or <, though.

Why is sizeof larger than my members added together?

The compiler inserts padding so each member is correctly aligned for the processor.

Is sorting pointers always faster?

For large records, yes. For tiny records the extra indirection can cost as much as it saves.

Does sorting through pointers change my data?

No. Only the pointer array is rearranged; the records stay where they are.

Which sorting algorithm should I use for embedded systems?

Simple algorithms suit small tables; for bigger ones use the standard qsort function, which you will meet in the next lecture.

Free Embedded C Course, Step by Step

Keep building with the free C programming course made for students and working engineers.

💬 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 →