offsetof简介

#define offsetof(s,m) (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m))

该宏用于求结构体中一个成员在该结构体中的偏移量。第一个参数是结构体的名字,第二个参数是结构体成员的名字。该宏返回结构体structName s中成员memberName(m)的偏移量。偏移量是size_t类型的。

offsetof returns the offset in bytes of the specified member from the beginning of its parent data structure. It is undefined for bit fields.

示例

#include <stdio.h>
#include <stddef.h>
typedef struct
{
int iVal;
int iVal2;
}Test;
typedef struct
{
char ch;
int iNum;
}Test2;
int main(void)
{
Test t = {1, 2};
Test2 t2 = {'t', 100};
printf("\naddress of t : %p\naddress of t.iVal : %p\naddress of t.iVal2: %p\n\n", &t, &(t.iVal), &(t.iVal2));
printf("offset of iVal in t: %p\n", offsetof(Test, iVal));
printf("offset of iVal2 in t: %p\n", offsetof(Test, iVal2));
printf("\naddress of t2 : %p\naddress of t2.ch : %p\naddress of t2.iNum: %p\n\n", &t, &(t2.ch), &(t2.iNum));
printf("offset of ch in t2: %p\n", offsetof(Test2, ch));
printf("offset of iNum in t2: %p\n", offsetof(Test2, iNum));
return 0;
}

 

  wps_clip_image-31628

 

  注意内存对齐。

原文

http://www.cppblog.com/lovedday/archive/2007/09/24/32801.html

http://baike.baidu.com/view/5513779.htm

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值