🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Sorting Strings by Swapping Pointers
Sort a list of strings in C without moving a single character. Learn selection sort with strcmp and the standard qsort function on an array of pointers, in our free C programming course.
How do you sort strings in C efficiently? The answer in embedded C programming is to leave the text alone and sort the pointers. Exchanging 4 or 8 byte addresses is far cheaper than copying whole strings, and the strings themselves never move. This lecture of our free embedded C course builds a selection sort with strcmp, proves the text never moved, and then does the same job with qsort.
What You Will Learn
- How to compare strings with
strcmpand read its result - How selection sort works on an array of pointers
- Why swapping pointers is cheaper than swapping strings
- How to write a correct comparator for
qsort - Common traps with comparator casts
Prerequisites
Finish the lectures on string functions (cp9_8 to cp9_12), arrays of pointers to strings (cp9_24), and sorting from the Arrays chapter (selection sort in cp7_32 onwards).
Comparing Strings with strcmp
Never compare strings with ==. That compares addresses, not text. Use strcmp(a, b), which returns a negative number if a comes before b, zero if they are equal, and a positive number if a comes after b. The comparison is by character code, so uppercase letters sort before lowercase ones.
Why Sort the Pointers
The text boxes are the same in both pictures. Only the arrows changed. With a 2-D char array you would instead copy up to 10 or 20 bytes per swap, three times per exchange.
Complete Program: Selection Sort and qsort
Save as sort_cmds.c:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 5
static void show(const char *tag, const char *const list[], size_t n)
{
printf("%-7s:", tag);
for (size_t i = 0; i < n; i++)
printf(" %s", list[i]);
printf("\n");
}
static int cmp_text(const void *a, const void *b)
{
const char *const *pa = a;
const char *const *pb = b;
return strcmp(*pa, *pb);
}
int main(void)
{
const char *cmds[N] = { "reset", "flash", "erase", "status", "boot" };
const char *copy[N] = { "reset", "flash", "erase", "status", "boot" };
const char *reset_ptr = cmds[0];
show("before", cmds, N);
for (int i = 0; i < N - 1; i++) {
int min = i;
for (int j = i + 1; j < N; j++)
if (strcmp(cmds[j], cmds[min]) < 0)
min = j;
if (min != i) {
const char *tmp = cmds[i]; /* swap pointers only */
cmds[i] = cmds[min];
cmds[min] = tmp;
}
}
show("sorted", cmds, N);
int same = 0;
for (int i = 0; i < N; i++)
if (cmds[i] == reset_ptr)
same = 1;
printf("\"reset\" string never moved: %s\n", same ? "yes" : "no");
qsort(copy, N, sizeof copy[0], cmp_text);
show("qsort", copy, N);
return 0;
}
gcc -std=c11 -Wall -Wextra -pedantic -o sort_cmds sort_cmds.c
./sort_cmds
Expected output:
before : reset flash erase status boot
sorted : boot erase flash reset status
"reset" string never moved: yes
qsort : boot erase flash reset status
How the selection sort works
- For position
i, scan the rest of the list and remember the indexminof the alphabetically smallest string - If the smallest one is not already at
i, swap the two pointers - Move to the next position and repeat until only one element remains
The program also keeps reset_ptr, the original address of "reset", and after sorting it finds the same address somewhere in the array. That proves the sorting changed only the order of addresses.
| Pass | Smallest found | Array after the pass |
|---|---|---|
| 1 | boot | boot flash erase status reset |
| 2 | erase | boot erase flash status reset |
| 3 | flash | boot erase flash status reset (already placed) |
| 4 | reset | boot erase flash reset status |
Sorting with qsort
The standard library already contains a sorting function. qsort needs the array, element count, element size, and a comparator function. The comparator receives pointers to two array elements. Because each element is itself a const char *, the comparator argument is a pointer to a pointer. That is why we cast to const char *const * and dereference once before calling strcmp.
The classic bug: passing strcmp directly to qsort. strcmp expects the string addresses, but qsort supplies the slot addresses. The sort silently compares garbage. Always write a wrapper that dereferences once.
Selection Sort vs qsort
| Point | Selection sort | qsort |
|---|---|---|
| Code | You write about 12 lines | One call plus a comparator |
| Speed on large lists | Quadratic, slow | Typically n log n |
| Stable for equal strings | Not guaranteed | Not guaranteed |
| Best use | Learning, tiny lists | Real programs |
Real-World Use Cases
- Listing files in alphabetical order in a Linux utility
- Sorting device names before printing a status report
- Keeping a command table sorted so a binary search can find commands fast
- Ordering log tags before grouping them
Common Mistakes and Troubleshooting
- Using == on strings. It compares addresses. The sort order will look random.
- Swapping the text with strcpy. Needless work and it fails on literals.
- Wrong comparator type. Compile with
-Wall -Wextrato catch mismatched casts. - Sorting a table declared
static const. A read-only table cannot be reordered. Sort a copy, as we did withcopy[]. - Uppercase surprises.
"Zebra"sorts before"apple"withstrcmp. Usestrcasecmpon POSIX systems for case-insensitive order.
Performance Considerations
Each swap exchanges one pointer, a handful of bytes, regardless of string length. Comparisons dominate the cost, so for lists with long shared prefixes strcmp itself can be the bottleneck. If you must sort millions of strings, qsort or a merge sort is the right choice and selection sort is not.
Best Practices
- Sort the pointers, not the characters
- Prefer
qsortfor anything beyond a few elements - Keep the original table read-only and sort a working copy
- Write a named comparator function and unit test it
Try It Yourself: Sorting Experiments
- Count the swaps. Add a counter to the selection sort and print it. For the five command names above the loop performs 4 passes and at most 4 swaps, which shows how few exchanges the algorithm needs.
- Descending order. Change the comparison from
< 0to> 0and predict the result before running it. You should get status, reset, flash, erase, boot. - Case-insensitive sort. Add the names “Zebra” and “apple” and observe where
strcmpplaces them. Then trystrcasecmpfrom the POSIX headerstrings.hand compare the two orders. - Sort by length. Write a second comparator that orders strings by
strlenfirst and alphabetically second. Plug it into the same qsort call. This shows that the sorting code and the ordering rule are separate ideas.
Each experiment changes one thing, so if the output surprises you it is easy to find the reason. That habit of changing one variable at a time is exactly how firmware engineers debug real hardware.
Summary and Key Takeaways
- Compare strings with
strcmp, never with== - Sorting an array of pointers moves only addresses
- The qsort comparator receives pointers to pointers
- A
consttable cannot be sorted in place
The final lecture of this chapter covers sprintf and its safe cousin snprintf, followed by a quiz and interview questions for the whole Strings chapter section.
Frequently Asked Questions
How do I sort strings alphabetically in C?
Keep them in an array of pointers, compare with strcmp, and either write a selection sort or call qsort with a comparator.
Why sort pointers instead of copying strings?
Swapping pointers moves a few bytes, while swapping strings copies every character.
Can I pass strcmp straight to qsort?
No. qsort passes the address of each array slot, so you need a wrapper that dereferences once.
Why does uppercase sort first?
strcmp compares character codes, and uppercase letters have smaller codes than lowercase ones.
Is qsort available on embedded targets?
Yes in most C libraries, but it may need extra stack. Check your library on very small devices.
Free Embedded C Course for Students
Next in our free c programming course: formatting text into buffers with sprintf and snprintf.

2 Comments