Simvik

Command table lookup

Find a command by name in a table and call its handler. A medium embedded C problem (Function pointers and state machines), run and graded in the browser.

medium · Function pointers and state machines · dispatch-table · cli

A serial console maps command names to handler functions with a table of command_t.

Search the n entries of table for a command whose name equals name exactly, call its handler with arg and return the handler's result. Return -1 if no entry matches or the matching entry has a NULL handler.

Starter code

int run_command(const command_t *table, size_t n, const char *name, int arg) {
  // Find the entry whose name matches and call its handler.
  return -1;
}

Example tests

First command

const command_t t[] = { { "led", cmd_led }, { "reset", cmd_reset } };
printf("%d\n", run_command(t, 2, "led", 21));

Expected output:

42

Second command

const command_t t[] = { { "led", cmd_led }, { "reset", cmd_reset } };
printf("%d\n", run_command(t, 2, "reset", 0));

Expected output:

100

Learn it first

More Function pointers and state machines problems