C/C++ Arena

Step 5 of 6

Generic code with void *

qsort works on any type because it treats the array as raw bytes: a void * base pointer plus an element size. Element i starts at byte offset i * size:

const char *bytes = base;            // char * allows byte arithmetic
const void *elem = bytes + i * size;

You can't do arithmetic on void * itself in standard C, which is why you go through char *.

Your turn: write find_first, which returns a pointer to the first element for which pred returns nonzero, or NULL.

Previous: Sorting with qsort Next: Challenge: an event bus