Tricky Tricks ›› Programming Tricks ›› C Languages Tricks ›› Sorting Strings With Qsort()

Sorting Strings With Qsort()

C Programming Tricks

Sorting strings with qsort():

On a more practical note, a C programmer usually encounters function pointers for the first time when dealing with the qsort() function. Often, the problem is to sort strings;

 const char **base;
 int nel;
 qsort(base, nel, sizeof (char *), strcmp) /* Wrong! */
 

seems like a perfect candidate for the job, and it usually compiles; but it doesn't work as expected! Figuring out why it doesn't work leads to better understanding of pointers and is a good investment of time; I will not include a complete explanation here and will just provide the correct solution:

 /* of course this function can be written in one line... */
 int strptrcmp (void *p1, void *p2)
 {
     const char *s1 = *((const char **) p1);
     const char *s2 = *((const char **) p1);
 
     return (strcmp (s1, s2));
 }
 
 /* ... */
 const char **base;
 int nel;
 qsort(base, nel, sizeof (char *), strptrcmp);
 

Partners