Simvik

From a member to its container

Recover a pointer to a struct from a pointer to one of its members. A hard embedded C problem (Pointers), run and graded in the browser.

hard · Pointers · offsetof · intrusive-list

An intrusive list links objects through a list_node_t embedded inside each one. Walking the list gives you a pointer to the embedded node, and you need the object around it.

Given a pointer to the node member of a task_t, return a pointer to that task_t.

Starter code

task_t *task_from_node(list_node_t *node) {
  // `node` points at the `node` member inside some task_t. Return that task_t.
  return NULL;
}

Example tests

One task

task_t t = { .id = 42, .priority = 3 };
task_t *p = task_from_node(&t.node);
printf("%d %u\n", p == &t, p->id);

Expected output:

1 42

Member values survive the round trip

task_t t = { .id = 7, .priority = 1, .deadline = 5000 };
task_t *p = task_from_node(&t.node);
printf("%u %u %u\n", p->id, p->priority, p->deadline);

Expected output:

7 1 5000

Learn it first

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

More Pointers problems