offsetof的原型为:
size_t offsetof(type, member);
DESCRIPTION
The macro offsetof() returns the offset of the field member from the
start of the structure type.
This macro is useful because the sizes of the fields that compose a
structure can vary across implementations, and compilers may insert
different numbers of padding bytes between fields. Consequently, an
element's offset is not necessarily given by the sum of the sizes of
the previous elements.
A compiler error will result if member is not aligned to a byte bound‐
ary (i.e., it is a bit field).
RETURN VALUE
offsetof() returns the offset of the given member within the given
type, in units of bytes.
CONFORMING TO
C89, C99, POSIX.1-2001.
以上内容摘自开发文档。
大意就是获取结构体成员member在结构体type中的偏移量。
其实offsetof就是一个宏定义,我们也可以自己实现的。接下来就来分析这个宏的具体实现。
struct type{
int a;
int b;
int member;
int c : 1;
}
#define offsetof(type, member) (size_t)&(((type *)0)->member)
type是一个结构体,定义如上所示,它有一个member成员,返回的是结构体type的成员member相对type的偏移地址。
这里的一个妙处就:(type *)0骗编译器说有一个指向结构体type的指针,地址值是0。
然后在取该指针的member地址 &((type *)0)->member,因为基址是0,所以这时member的地址就是member在type中的偏移量了。
最后转换成size_t型,即unsigned int。