Writing a string comparison function for qsort
What you'll learn: How to correctly bridge the gap between qsort's generic pointer requirements and the strcmp function to sort lists of text.
Sorting numbers is straightforward, but sorting strings is a classic "gotcha" in C. Because qsort is designed to be generic—meaning it can sort anything from integers to complex space-shuttle telemetry—it deals exclusively in void * (generic pointers). To sort strings, we need to write a specific "translator" function that tells qsort how to handle them.
The "Double Pointer" Hurdle
When you sort an array of strings in C, you are usually sorting an array of char *. When qsort compares two elements, it passes pointers to those elements to your comparison function.
Think of it like this: If your array is a row of mailboxes, and each mailbox contains a letter (a string), qsort doesn't hand you the letters directly. Instead, it hands you the addresses of two mailboxes. To read the letters, you must first look at the address, then open the box. In C terms, this means your comparison function receives a void * that is actually a char ** (a pointer to a pointer).
The Implementation
To make this work, your comparison function must follow three steps:
- Cast the generic
void *to achar **. - Dereference it to get the actual
char *(the string). - Pass those strings to
strcmp.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// The comparison function
int compare_strings(const void *a, const void *b) {
// 1. Cast and dereference to get the actual strings
const char *str1 = *(const char **)a;
const char *str2 = *(const char **)b;
// 2. Return the result of strcmp
return strcmp(str1, str2);
}
int main() {
const char *planets[] = {"Mars", "Earth", "Jupiter", "Venus"};
int count = 4;
qsort(planets, count, sizeof(char *), compare_strings);
for (int i = 0; i < count; i++) {
printf("%s ", planets[i]);
}
return 0;
}
Why the extra step?
If you tried to pass strcmp directly to qsort, the program would crash or behave erratically. This is because strcmp expects to receive the strings themselves, but qsort is stubbornly handing it the address where the string pointer is stored. By creating this small wrapper function, you provide the necessary translation that allows qsort to organize your text alphabetically.
Key takeaway
To sort strings with qsort, you must cast the input pointers to char ** and dereference them before using strcmp.