offset宏

【1】offset宏的作用?

答案:自己查MSDN(呵呵!我也不懂。)

查询结果如下:

Retrieves the offset of a member from the beginning of its parent structure.

size_t  offsetof(structName,  memberName);

Parameters 

structName: Name of the parent data structure.

memberName : Name of the member in the parent data structure for which to determine the offset.

Return Value

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

Remarks

The offsetof macro returns the offset in bytes of memberName from the beginning of the structure specified by structName. You can specify types with the struct keyword.

好吧!不要给我说看不懂,看不懂就想问你:“你好!大学四级没过吧?”

那么,关于这个查询结果的学习过程如下,假使定义了一个结构体:A,定义其指针pA。示例代码如下:

1 struct A
2 {
3     int i;
4     int j;
5 };
6 
7 struct A *pA;

这时,pA作为一个Pointer, 指向某一确定的内存地址,比如0x1234。
而 pA->i 整体是一个int型变量,其地址表示为&(pA->i) ,'&'为取址运算符; 
那么&(pA->i)一定等于0x1234,因为i是结构体A的第一个变量成员。 
而&(pA->j)一定是0x1234 + 0x4 = 0x1238。因为sizeof(int) = 4;

现在试想一下,我们把结构体的指针值如果作为0,会得到什么结果呢?

也就是说:

0------>(A *)0

原来是数值0,现在为结构体指针类型。尽管类型不同,但其值不变。

&(((A *)0)->j)求出字段j的地址值,但由于首地址是0。

所以,(size_t)(&(((A *)0)->j))值将是字段j相当于首地址的偏移值。

具体示例代码如下:

 1 #include<iostream>
 2 using  namespace std;
 3 
 4 #define  offset(s,a)   ((size_t)(&(((s *)0)->a)))
 5 
 6 struct  s
 7 {
 8     int  a;
 9     char d;
10     int  b;
11     char c;
12 };
13 
14 void main()
15 {
16     cout<<offset(s,c)<<endl;   //12
17 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值