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 42Member 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 5000Learn it first
- Pointers · Addresses, arithmetic, const, void pointers and object lifetime.
More Pointers problems
- Swap two values · Exchange two integers through pointers.
- Sum a pointer range · Walk a half-open range with a pointer.
- Pointer to the largest element · Return a pointer to the maximum of an array, or NULL when it is empty.
- Reverse a buffer in place · Reverse a byte buffer without a second buffer.
- Implement memset · Fill a block of memory with one byte value.
- Implement memcpy · Copy a block of bytes between two non-overlapping buffers.
- Implement memmove · Copy bytes correctly even when source and destination overlap.
- Advance a cursor · Move a caller's string pointer past leading whitespace.
- Generic swap · Exchange two objects of any type, byte by byte.
- Look up a record · Search an array of structs and return a pointer to the match.
- Fix the dangling pointer · Repair a function that returns the address of a local array.
- Align an address · Round an address up to a power-of-two boundary.
- Index a matrix through a pointer · Read an element of a 2-D array given only a pointer to its first element.
- Fix: the display shows garbage · A formatting function returns a pointer to its own local buffer.
- Fix: the first job is sometimes wrong · A function frees a list and then reads from it.