Concept
How can qsort() sort an array of strings using pointers?
ComputerScienceOne / Sorting Pointers to Elements
"A prime example of sorting an array of pointers to structures is sorting an array of strings. An array of strings can be thought of as a 2-dimensional array of chars. Specifically, an array of strings is a char ** type. That is, an array of pointers to pointers of chars. We may be tempted to use strcmp() in the standard string library, passing it to qsort(). Unfortunately this will not work. qsort() requires two const void * types, while strcmp() takes two const char * types. This difference is subtle but important. The recommended way of doing this is to define a different comparator function as in Code Sample 25.4.\n\n/* compare strings via pointers */\n\nint pstrcmp(const void *p1, const void *p2)\n\n{\n\nreturn strcmp(*(char * const *)p1, *(char * const *)p2);\n\n}\n\nObserve the behavior of this function: it uses the standard strcmp() function, but makes the proper explicit type casting before doing so. The *(char * const *) casts the generic void pointers as pointers to strings (or pointers to pointers to characters), then dereferences it to be compatible with strcmp()."
Related Ideas
- How can comparator functions order Student structures?ComputerScienceOne · Comparator Functions
- What is a comparator function and how does it determine element order?ComputerScienceOne · Comparator Functions
- How does the C standard library’s qsort() function work?ComputerScienceOne · Sorting
- How can you create an array of strings in C?ComputerScienceOne · Arrays of Strings
- How do you implement a comparator for integers in C?ComputerScienceOne · Comparator Functions
- How does strcmp() compare the contents of two strings in C?ComputerScienceOne · Comparisons
- How are qsort(), lfind(), and bsearch() used in C examples?ComputerScienceOne · Examples
- What is a function pointer and how is it declared?ComputerScienceOne · Function Pointers