Quiz Entry - updated: 2026.07.10
How do you find the offset of a member within a struct?
Use offsetof(struct T, member) from <stddef.h>, which gives the byte distance from the struct's start to that field (accounting for padding).
#include <stddef.h>
struct example {
// offset 0
char a;
// offset 4 (after 3 bytes padding)
int b;
// offset 8
char c;
};
// 0
size_t off_a = offsetof(struct example, a);
// 4
size_t off_b = offsetof(struct example, b);
// 8
size_t off_c = offsetof(struct example, c);
Use case: Convert member pointer back to struct pointer
#define container_of(ptr, type, member) \
((type *)((char *)(ptr) - offsetof(type, member)))
struct node {
int data;
struct node *next;
};
void process(int *data_ptr) {
// Get the struct that contains this data member
struct node *n = container_of(data_ptr, struct node, data);
printf("Next: %p\n", n->next);
}
This is how Linux kernel linked lists work!
Manual offsetof (how it works internally):
#define my_offsetof(type, member) \
((size_t)&((type *)0)->member)
// Takes address of member in a struct at address 0