CONTAINER_OF(3) Library Functions Manual CONTAINER_OF(3)

container_ofcast a pointer to member of a structure to a pointer of its container structure.

#include <sys/container_of.h>

type *
container_of(pointer, type, member);

Given a pointer that points to a member of the container structure type the () macro returns a pointer that points to the enclosing container structure.

A compiler error will result if member is not aligned to a byte boundary (i.e. it is a bit-field).

#include <assert.h>
#include <sys/container_of.h>
struct container {
        double  other_member;
        int     member;
};

struct container one;

void test(void) {
        int *ptr = &one.member;
        struct container *onep = container_of(ptr, struct container, member);
        assert(onep == &one);
}

__alignof__(3), offsetof(3), stddef(3), typeof(3)

The container_of() macro appeared first in the Linux kernel.

October 8, 2011 NetBSD 11.0