Generic minimum
Find the smallest element of an array of any type using a comparator. A medium embedded C problem (Function pointers and state machines), run and graded in…
medium · Function pointers and state machines · void-pointer · callbacks
Like qsort, this function knows nothing about the element type. It is given the address of the array (base), the number of elements (n), the size of one element in bytes (size) and a comparator.
cmp(a, b) returns a negative value if *a is smaller than *b, zero if they are equal and a positive value otherwise. Return a pointer to the smallest element, the first one if several are equal, or NULL if n is 0.
Starter code
const void *find_min(const void *base, size_t n, size_t size, int (*cmp)(const void *, const void *)) {
// Element i starts `i * size` bytes after base.
return NULL;
}Example tests
16-bit signed values
const int16_t a[] = { 5, -2, 9 };
const int16_t *m = find_min(a, 3, sizeof a[0], cmp_i16);
printf("%d %d\n", *m, (int)(m - a));Expected output:
-2 132-bit unsigned values
const uint32_t a[] = { 70000, 3, 4000000000u };
const uint32_t *m = find_min(a, 3, sizeof a[0], cmp_u32);
printf("%u %d\n", *m, (int)(m - a));Expected output:
3 1Learn it first
- Function pointers and callbacks · Callbacks, dispatch tables and the context pointer that makes them reusable.
More Function pointers and state machines problems
- Dispatch through a vector table · Call the handler registered for an interrupt number, with a safe fallback.
- Replace a switch with a table · Select an operation by opcode using an array of function pointers.
- Apply a function to a buffer · Transform every element of an array with a caller-supplied function.
- Command table lookup · Find a command by name in a table and call its handler.
- Sort with a comparator · Sort an array into an order defined by a callback.
- State transition function · Implement the transition rules of a motor controller.
- Publish and subscribe · Keep a fixed-size list of callbacks and notify them in order.
- Callback with context · Invoke a callback for every set bit, passing through a user context.
- State handlers · Build a state machine in which each state is a function.
- TV remote: a table of key actions · Look a key code up in a table and call its action with the device's context.