#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
来源:互联网 发布:计算器程序单片机 编辑:程序博客网 时间:2024/04/28 15:55
#define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
上述宏是什么意思?
计算 STRUCTURE 类型中 FIELD 域的偏移量
下面拿KEIL 8051的定义来作点解释:
((s *)0):强制转化成数据结构指针,并使其指向地址0;
((s *)0)->m:使该指针指向成员m
&(((s *)0)->m):获取该成员m的地址
(size_t)&(((s *)0)->m):转化这个地址为合适的类型
你可能会迷惑,这样强制转换后的结构指针怎么可以用来访问结构体字段?呵呵,其实这个表达式根本没有也不打算访问m字段。ANSI C标准允许任何值为0的常量被强制转换成任何一种类型的指针,并且转换结果是一个NULL指针,因此((s*)0)的结果就是一个类型为s*的NULL指针。如果利用这个NULL指针来访问s的成员当然是非法的,但&(((s*)0)->m)的意图并非想存取s字段内容,而仅仅是计算当结构体实例的首址为((s*)0)时m字段的地址。聪明的编译器根本就不生成访问m的代码,而仅仅是根据s的内存布局和结构体实例首址在编译期计算这个(常量)地址,这样就完全避免了通过NULL指针访问内存的问题。又因为首址的值为0,所以这个地址的值就是字段相对于结构体基址的偏移。
这里有个地方需要注意:就是offsetof虽然同样适用于union结构,但它不能用于计算位域(bitfield)成员在数据结构中的偏移量。
typedef struct
{
unsigned int a:3;
unsigned int b:13;
unsigned int c:16;
}foo;
使用offset(foo,a)计算a在foo中的偏移量,编译器会报错。
文章出处:飞诺网(www.firnow.com):http://dev.firnow.com/course/6_system/linux/Linuxjs/20090314/161436.html
- #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
- field define
- attempt to reference field of non-structure array
- [Matlab]Attempt to reference field of non-structure array
- 字段符号(FIELD SYMBOLS)和 结构体继承INCLUDE STRUCTURE
- structure
- How can I determine the byte offset of a field within a structure?
- 【已解决】我遇到的 bad flag(parameter or structure field)(Unrecognized or unsupported array type)
- matlab 2013a 出现Attempt to reference field of non-structure array
- OpenCV Error::: bad flag(parameter or structure field)(Unrecognized or unsupported array type)
- 关于opencv的“Bad flag (parameter or structure field)...“
- Field
- a simple cmdline implementation method--structure define
- int( (LONG)(LONG_PTR)&(((type *)0)->field))的最好解释
- int( (LONG)(LONG_PTR)&(((type *)0)->field))的最好解释
- int( (LONG)(LONG_PTR)&(((type *)0)->field))的最好解释
- lucene3.0中Field.Index, Field.Store,Field.TermVector详解
- Calendar.clear(int field)的陷阱
- 配置apache HIVE元数据DB为PostgreSQL
- 辉光管电子时钟
- 算法导论 递归树计算复杂度
- Linux 2.6 内存管理源码分析(5)
- 永远年轻,永远热泪盈眶。
- #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
- 精神
- weblogic10.3安装FOR AIX
- poj 1125 floyed算法
- Section 1.1 Broken Necklace
- 学习笔记------------------------自定义拦截器
- 比你拼命的人多的是,最可怕的是比你牛的人比你还拼命(每天看一段一个月刚刚好)
- gdb调试多进程 gdb 多进程 多线程调试方法 gdb调试
- 如何设置Eclipse工作空间的缺省字符编码?