再次理解offsetof的实现原理

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。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值