Challenges/Memory & Types/offsetof and Field Access

offsetof and Field Access

๐ŸŸก Standard

offsetof and Field Access

Implement `get_field_offset` which, given a pointer to a struct and a field name, returns the byte offset of that field from the start of the struct. Use the `offsetof` macro from `<stddef.h>`.

Then implement `read_field_u32` that reads a `uint32_t` from a struct at a given byte offset.

typedef struct {

uint8_t id;

uint32_t value;

uint16_t checksum;

} Packet;

Why it matters: offsetof is used in Linux kernel internals (`container_of`), device driver frameworks, and serialization libraries.

example
typedef struct {
    uint8_t  id;
    uint32_t value;
    uint16_t checksum;
} Packet;

Test Cases

1.
value field offset must be 4 (after 1 byte id + 3 padding)
get_value_offset() == 4
2.
read_u32_at reads correct value
read_u32_at(&p, 4) == p.value
solution.c