Simvik

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 1

32-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 1

Learn it first

More Function pointers and state machines problems