offsetof 宏的简介
来源:互联网 发布:极光推送 php接口实例 编辑:程序博客网 时间:2024/05/25 08:15
原文地址:http://baike.baidu.com/view/5513779.htm
定义
在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)) #endif #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 */
功能
该宏用于求结构体中一个成员在该结构体中的偏移量。
在msdn上,该宏被写作:
size_t offsetof( structName, memberName );
第一个参数是结构体的名字,第二个参数是结构体成员的名字。该宏返回结构体structName中成员memberName的偏移量。偏移量是size_t类型的。
程序示例
#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; }在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 : 0012FF10
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语言中内存对齐机制。
- offsetof 宏的简介
- offsetof宏的使用
- offsetof宏的用法
- offsetof宏
- offsetof宏
- C语言中offsetof宏的应用
- C语言中offsetof宏的应用
- C语言offsetof宏的说明
- C语言中offsetof宏的应用
- C语言中offsetof宏的应用
- linux 内核代码的offsetof()宏
- 两个重要的宏 offsetof 和 container_of
- offsetof宏的原理以及作用
- 关于offsetof()的warning!
- offsetof的实现
- offsetof函数的应用
- offsetof宏学习反思
- offsetof宏解析
- 一、如何使用变量给数据源控件参数赋值
- LinuxC/C++编程基础(14) asio定时器的用法
- ubuntu 下的PDF阅读器(超级好使)
- Java乔晓松-Servlet Filter(过滤器)
- SIFT算法 中文资料
- offsetof 宏的简介
- 描述事件监听机制
- VS2010如何设置使得可以是程序利用argv参数来运行
- stage.invalidate()、event.updateAfterEvent()对渲染的影响
- CKEditor 3.6入门--通过 javascript 调用CKEditor 编辑器
- Android中自定义Activity和Dialog的位置大小背景和透明度等
- js详解
- windows程序设计 例题解析 NOPOPUPS.C
- 进程原语和线程原语的比较