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().
Feed/

How can qsort() sort an array of strings using pointers?

No cover

Channel

Computer science one

1 page

"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()."

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.