Why does this implementation of offsetof() work?

2019-01-04 01:39发布

In ANSI C, offsetof is defined as below.

#define offsetof(st, m) \
    ((size_t) ( (char *)&((st *)(0))->m - (char *)0 ))

Why won't this throw a segmentation fault since we are dereferencing a NULL pointer? Or is this some sort of compiler hack where it sees that only address of the offset is taken out, so it statically calculates the address without actually dereferencing it? Also is this code portable?

7条回答
Evening l夕情丶
2楼-- · 2019-01-04 02:26

It calculates the offset of the member m relative to the start address of the representation of an object of type st.

((st *)(0)) refers to a NULL pointer of type st *. &((st *)(0))->m refers to the address of member m in this object. Since the start address of this object is 0 (NULL), the address of member m is exactly the offset.

char * conversion and the difference calculates the offset in bytes. According to pointer operations, when you make a difference between two pointers of type T *, the result is the number of objects of type T represented between the two addresses contained by the operands.

查看更多
登录 后发表回答