Bifalgorithm post · Computer science one · Sorting Pointers to Elements
How can qsort() sort an array of strings using pointers?
How can qsort() sort an array of strings using pointers? (Computer science one · Sorting Pointers to Elements) — "A prime example of sorting an array of pointe…
Ideas in this flowchart
- Sorting an array of strings requires a specialized comparator for qsort().
- An array of strings can be viewed as a two-dimensional array of chars.
- Its type is char**, meaning an array of pointers to pointers of chars.
- qsort() requires comparator arguments of type const void *.
- strcmp() takes arguments of type const char *.
- Passing strcmp() directly to qsort() does not work because the function signatures differ.
- The recommended solution is to define a separate comparator named pstrcmp().
- pstrcmp() receives two generic pointers and uses strcmp() to compare the strings.
- The expression *(char * const *) casts each generic pointer as a pointer to a string pointer and then dereferences it.
- The explicit cast produces arguments compatible with strcmp().