What does ((struct name *)0)->member) do in C?
The actual C statement I came across was this:
(char *) &((struct name *)0)->member)
This is a trick for getting the offset of struct's member called member. The idea behind this approach is to have the compiler compute the address of member assuming that the structure itself is located at address zero.
Using offsetof offers a more readable alternative to this syntax:
size_t offset = offsetof(struct name, member);
(struct name *)0 is casting 0 to pointer to struct name.&((struct name *)0)->member) is getting the address of member member.(char *) &((struct name *)0)->member) is casting that address to char *.
In case anyone thinks that the above expression is dereferencing a NULL pointer, then note that there is no dereferencing here. It's all for getting the address of member number.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With