Why subtract null pointer in offsetof()?

前端 未结 2 1952
面向向阳花
面向向阳花 2020-12-18 03:18

Linux\'s stddef.h defines offsetof() as:

#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

whereas the Wik

相关标签:
2条回答
  • 2020-12-18 04:16

    The standard does not require the NULL pointer to evaluate to the bit pattern 0 but can evaluate to a platform specific value.

    Doing the subtraction guarantees that when converted to an integer value, NULL is 0.

    0 讨论(0)
  • 2020-12-18 04:17

    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.

    BTW, I was the editor that added the original code to the Wiki entry, which was the Linux form. Later editors changed it to the more portable version.

    0 讨论(0)
提交回复
热议问题