你是否正在寻找关于offsetof的内容?让我把最俱价值的东西奉献给你:
offsetof :
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.
Note :
offsetof is not a function and cannot be described using a C prototype.
#define offsetof(s, m) (size_t)&(((s *)0)->m)
s是一个结构名,它有一个名为m的成员(s和m 是宏offsetof的形参,它实际是返回结构s的成员m的偏移地址.
(s *)0 是骗编译器说有一个指向类(或结构)s的指针,其地址值0
&((s *)0)->m 是要取得类s中成员变量m的地址. 因基址为0,这时m的地址当然就是m在s中的偏移
最后转换size_t 型,即unsigned int,。
有例子如:
struct A
{
int i;
int j;
};
struct A *pA;
pA = new A;
这时,pA实际上是一个Pointer, 指向某一确定的内存地址, 如0x1234;
而pA->i 整体是一个int型变量,其地址是&(pA->i), '&'为取址运算符;
那么&(pA->i)一定等于0x1234,因 i 是结构体A的第一个元素。
而&(pA->j)一定是0x1234 + 0x4 = 0x1238; 因为sizeof(int) = 4;
这个做法的巧妙之处就是:它把“0”作为上例中的pA,那么&(pA->j)就是 j 的offset
解析结果是:
(s*)0,将 0 强制转换为Pointer to "s"
可以记 pS = (s*)0,pS是指向s的指针,它的值是0;
那么pS->m就是m这个元素了,而&(pS->m)就是m的地址,就是offset
下面是个offsetof应用的例子,其中宏OBJECT_HEAD_ADDRES的作用是根据一个对象或结构的某成员的地址,求其首地址。
完整的例子如下:
/* offsetof example */
#include "stdafx.h"
#include
以上就是关于offsetof的全部内容,相信你一定会非常满意。
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/shenmilingyu/article-6825-1.html
如果他要耍赖
男生女生都爱