Why subtract null pointer in offsetof()?

前端 未结 2 1953
面向向阳花
面向向阳花 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: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.

提交回复
热议问题