liveBook · Manning

Qsort

As explained in Modern C

qsort is a C standard library function that sorts an array using a caller-provided comparison function.

qsort sorts an array through a caller-provided comparison function. It accepts the array base as a void pointer, the element count, the element size, and a comparator, allowing one interface to handle many data types. section 11.4

Use the interface correctly by preserving the comparator contract:

  • Pass the address of the first element, the number of elements, and the size of each element. section 11.4
  • Write a comparator receiving two const void pointers and returning a negative value, zero, or a positive value for less-than, equality, or greater-than. section 11.4
  • Compare values consistently after converting the void pointers to the array’s element type; do not implement integer ordering by subtracting values, because the subtraction may overflow. section 11.4

Sorting unsigned values

A type-specific wrapper can call qsort(base, nmeb, sizeof base[0], compare_unsigned), while compare_unsigned casts its arguments to unsigned pointers and returns -1, 0, or +1 through explicit comparisons.

How Modern C covers it

How deep it goes
Defines parameters and comparator rules, then warns about overflow but defers the sorting algorithm’s internals.
Examples
Uses unsigned comparison, an invalid subtracting integer comparator, and a type-specific qsort wrapper.
What it assumes
Assumes arrays, pointers, void pointers, and function-pointer syntax while illustrating their roles in the interface.
What you can do after
Apply it via the C standard library by supplying correctly sized elements and a consistent comparator.
How it connects
Connects qsort with function pointers, void pointers, arrays, comparison functions, and bsearch.

Also explained in

Compare how 2 books explain qsort →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.