liveBook · Manning

Qsort

As explained in Modern C, Third Edition

qsort is a C standard library function that sorts the elements of an array using a caller-supplied comparison function.

qsort sorts an array in place through a generic interface: pass the base address, element count, element size, and a function pointer that defines ordering. section 11.4

A safe comparison function

The comparator receives pointers to two elements. Return a negative value when the first precedes the second, zero when they compare equal, and a positive value otherwise. Compare explicitly rather than returning *A - *B, which can overflow for extreme int values.

Because qsort receives the array as void* and loses its element type, size must describe each element correctly and the comparator must interpret that element type consistently. section 11.4

How Modern C, Third Edition covers it

How deep it goes
Explains parameters, comparator results, type erasure, and overflow safety, but does not describe the sorting algorithm's implementation.
Examples
Uses unsigned comparison and contrasts explicit ordering tests with an overflowing integer subtraction comparator.
What it assumes
Assumes familiarity with arrays, pointers, void pointers, and function pointers while defining the comparator convention explicitly.
What you can do after
Apply it via the C standard library by supplying correctly sized elements and a consistent, overflow-safe comparator.
How it connects
Connects qsort with function pointers, void pointers, comparison functions, arrays, 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, Third Edition. The section links point to the parts of the book it draws on.