Description#
The null pointer trick is a classic C programming technique that allows you to access a struct member’s offset or size without creating an actual instance of the struct.
Example#
Let’s say you have a struct like this:
struct Name {
int member;
};
And you want to get the size of the member
field without creating an instance
sizeof(((struct Name *)0)->member)
How it works:#
(struct Name *)0
casts the integer value 0 to a pointer to your struct- The
->member
accesses a field of this hypothetical struct “located” at memory address 0 sizeof()
evaluates the size of the member’s type at compile time
Alternative:#
In modern C, you can use the offsetof
macro from stddef.h
to achieve the same:
#include <stddef.h>
offsetof(struct Name, member)