複製鏈接
請複製以下鏈接發送給好友

offsetof

鎖定
offsetof,程序語言,該宏用於求結構體中一個成員在該結構體中的偏移量
中文名
外文名
offsetof
領    域
計算機
性    質
函數類型

目錄

offsetof定義

stddef.h頭文件中,該宏的完整説明如下:
#ifdef __cplusplus
#ifdef _WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&reinterpret_cast<const volatile char&>((((s *)0)->m)) )
#else
#define offsetof(s,m) (size_t)&reinterpret_cast<const volatile char&>((((s *)0)->m))
#else
#ifdef _WIN64
#define offsetof(s,m) (size_t)( (ptrdiff_t)&(((s *)0)->m) )
#else
#define offsetof(s,m) (size_t)&(((s *)0)->m)
#endif
#endif /* __cplusplus */

offsetof功能

在msdn上,該宏被寫作:
size_t offsetof( structName, memberName );
第一個參數是結構體的名字,第二個參數是結構體成員的名字。該宏返回結構體structName中成員memberName的偏移量。偏移量是size_t類型的。

offsetof程序示例

#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: %d\n", offsetof(Test, iVal));
printf("offset of iVal2 in t: %d\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: %d\n", offsetof(Test2, ch));
printf("offset of iNum in t2: %d\n", offsetof(Test2, iNum));
return 0;
}
VS2005中輸出:
address of t : 0012FF10
address of t.iVal : 0012FF10
address of t.iVal2: 0012FF14
offset of iVal in t: 00000000
offset of iVal2 in t: 00000004
address of t2 : 0012FF00
address of t2.ch : 0012FF00
address of t2.iNum: 0012FF04
offset of ch in t2: 00000000
offset of iNum in t2: 00000004
需要注意的是,Test2中iNum成員的偏移量是4而不是1,這涉及到C語言中內存對齊機制。