1.\" $NetBSD: container_of.3,v 1.2 2024/10/09 00:55:24 uwe Exp $ 2.\" 3.\" Copyright (c) 2024 The NetBSD Foundation, Inc. 4.\" All rights reserved. 5.\" 6.\" Redistribution and use in source and binary forms, with or without 7.\" modification, are permitted provided that the following conditions 8.\" are met: 9.\" 1. Redistributions of source code must retain the above copyright 10.\" notice, this list of conditions and the following disclaimer. 11.\" 2. Redistributions in binary form must reproduce the above copyright 12.\" notice, this list of conditions and the following disclaimer in the 13.\" documentation and/or other materials provided with the distribution. 14.\" 15.\" THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 16.\" ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 17.\" TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 18.\" PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 19.\" BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 20.\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 21.\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 22.\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 23.\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 24.\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 25.\" POSSIBILITY OF SUCH DAMAGE. 26.\" 27.Dd October 8, 2011 28.Dt CONTAINER_OF 3 29.Os 30.Sh NAME 31.Nm container_of 32.Nd cast a pointer to member of a structure to a pointer of its 33container structure. 34.Sh SYNOPSIS 35.In sys/container_of.h 36.Ft "type *" 37.Fn container_of "pointer" "type" "member" 38.Sh DESCRIPTION 39Given a 40.Fa pointer 41that points to a 42.Fa member 43of the container structure 44.Fa type 45the 46.Fn container_of 47macro returns a pointer that points to the enclosing container structure. 48.Pp 49A compiler error will result if 50.Ar member 51is not aligned to a byte boundary 52.Pq i.e. it is a bit-field . 53.Sh EXAMPLES 54.Bd -literal 55#include <assert.h> 56#include <sys/container_of.h> 57struct container { 58 double other_member; 59 int member; 60}; 61 62struct container one; 63 64void test(void) { 65 int *ptr = &one.member; 66 struct container *onep = container_of(ptr, struct container, member); 67 assert(onep == &one); 68} 69.Ed 70.Sh SEE ALSO 71.Xr __alignof__ 3 , 72.Xr offsetof 3 , 73.Xr stddef 3 , 74.Xr typeof 3 75.Sh HISTORY 76The 77.Fn container_of 78macro appeared first in the Linux kernel. 79