为什么offsetof减去空指针()? [英] Why subtract null pointer in offsetof()?
问题描述
的Linux的<一个href=\"http://google.com/$c$csearch/p?hl=en#huut-anHVuo/anonymous/kernel/v2.6/linux-2.6.20.tar.bz2%7CqE0cR-WvTpY/linux-2.6.20/include/linux/stddef.h&q=stddef.h%20linux-2.6\"相对=nofollow> STDDEF.H 定义 offsetof()
为:
Linux's stddef.h defines offsetof()
as:
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)
而在维基百科的文章offsetof()
( http://en.wikipedia.org/wiki/Offsetof ),其定义为:
#define offsetof(st, m) \
((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))
为什么在维基百科版本减去(的char *)0
?是否存在这样一种真的有所作为无论如何?
Why subtract (char *)0
in the Wikipedia version? Is there any case where that would actually make a difference?
推荐答案
第一个版本的指针转换为具有铸造,这是不可移植的一个整数。
The first version converts a pointer into an integer with a cast, which is not portable.
第二个版本是在较宽各种编译器更便携,因为它依赖于指针运算由编译器来获得一个整数结果,而不是一个类型转换的。
The second version is more portable across a wider variety of compilers, because it relies on pointer arithmetic by the compiler to get an integer result instead of a typecast.
的顺便说一句,我是添加了原code维基条目,这是Linux的形式编辑器。后来编辑改成了更便携版本。的
这篇关于为什么offsetof减去空指针()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!