Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does ((struct name *)0)->member) do in C? [duplicate]

Tags:

c

pointers

struct

What does ((struct name *)0)->member) do in C?

The actual C statement I came across was this:

(char *) &((struct name *)0)->member)
like image 446
krisharav Avatar asked Feb 01 '16 16:02

krisharav


2 Answers

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);
like image 72
Sergey Kalinichenko Avatar answered Nov 15 '22 13:11

Sergey Kalinichenko


(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.

like image 33
haccks Avatar answered Nov 15 '22 12:11

haccks