Course contentsShow
← C
Lesson 876 of 1,21912. The Standard LibraryFree lesson

The generic signature of `qsort`

The generic signature of qsort

What you'll learn: How the qsort function uses void* pointers and function pointers to sort any type of data without knowing what that data is.

The Mystery Box Problem

Imagine you are a professional organizer. Someone hands you a row of 100 sealed cardboard boxes and says, "Sort these by weight." You have a problem: you don't know what's inside the boxes, and you aren't allowed to open them. To do your job, you need two things: the location of the boxes and a "scale" provided by the owner that tells you which of two boxes is heavier.

In C, the qsort function is that professional organizer. It is a "generic" function, meaning it can sort integers, floats, or even complex custom structures. However, because it was written long before you created your specific data, it uses a very specific signature to stay flexible.

Breaking Down the Signature

The declaration for qsort looks intimidating, but it follows a clear logic:

void qsort(
    void *base,           // Where does the array start?
    size_t nmemb,         // How many items are there?
    size_t size,          // How big is each individual item (in bytes)?
    int (*compar)(const void *, const void *) // The "scale" function
);

Because qsort doesn't know if you are sorting ints or struct SpaceShips, it treats your array as a raw block of memory.

  1. void *base: This is a pointer to the start of your array. By using void*, qsort says, "I don't care what type this is; just give me the memory address."
  2. size: Since void* has no type, qsort doesn't know how far to jump to get to the next element. You must tell it the size of one element (usually via sizeof) so it can do the math to find the second, third, and fourth items.
  3. compar: This is the "callback." Since qsort can't compare your data using < or >, you must provide a pointer to a function that takes two items and returns an integer indicating which is "larger."

Why the void* is Powerful

This design is a masterclass in abstraction. By using void* in both the main function and the comparison function, qsort never needs to be rewritten. You do the heavy lifting of casting the "mystery box" pointers back to your actual data type inside your comparison function, and qsort handles the complex logic of moving those items around in memory.

Key takeaway

qsort uses void* pointers and a size argument to navigate memory blindly, relying on your custom comparison function to understand the actual data.