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 qsort() sort an array of strings using pointers? | ComputerScienceOne | Bifalgorithm | Bifalgorithm