OFFSET OF MACRO in C [offsetof(TYPE, MEMBER)]

Here I am going to discuss an interesting macro in C. It will give you offset of a member within a structure.

NULL or 0 address is typecasted to TYPE first. This won't result in segmentation fault as we are not going to access value at 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 actually 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 actually exists there, then afterward we are reading the address of that member. This will give you the offset because the members 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)

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.