Simvik

Look up a record

Search an array of structs and return a pointer to the match. An easy embedded C problem (Pointers), run and graded in the browser.

easy · Pointers · structs · arrow-operator

Return a pointer to the entry of table whose id matches, or NULL if no entry does. The table has n entries.

The caller uses the pointer to update the entry in place, so it must point into the table, not at a copy.

Starter code

sensor_t *find_sensor(sensor_t *table, size_t n, uint8_t id) {
  // Return the address of the matching entry, or NULL.
  return NULL;
}

Example tests

Entry exists

sensor_t t[] = { { 1, 100 }, { 7, -50 }, { 9, 300 } };
sensor_t *s = find_sensor(t, 3, 7);
printf("%d %d\n", (int)(s - t), s->value);

Expected output:

1 -50

Entry is missing

sensor_t t[] = { { 1, 100 }, { 7, -50 }, { 9, 300 } };
printf("%s\n", find_sensor(t, 3, 4) ? "found" : "null");

Expected output:

null

Learn it first

  • Pointers · Addresses, arithmetic, const, void pointers and object lifetime.

More Pointers problems