Here I am going to discuss an exciting macro in C. It will give you offset of a member within a structure.
NULL or 0 address is typecasted to TYPE first. It won't result in segmentation fault as we are not going to access the value at the NULL address. By typecasting NULL to TYPE, you can imagine that an object of type TYPE is residing at 0 address location. Now, after that, if you access the member's address, it will give you the offset. Since we are typecasting 0 address location to TYPE, we are forcing the compiler to think that an object of type TYPE exists there, then afterwards we are reading the address of that member. It will give you the offset because the member's address is calculated relative to 0. Since we are not accessing memory at that location and merely fetching the address, it won't result in segmentation fault due to invalid memory access.
typedef struct
{
int i;
float f;
char c;
} SFOO;
void main(void)
{
printf("Offset of 'f' is %u", offsetof(SFOO, f));
}
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)