offsetof macro in C

I just discovered this macro available in C: offsetof. Here is an simple example:

struct
{
  char a;
  int b;
  char c;
} example;
 
struct example s1;
 
unsigned int offset;
offset = (unsigned int)(&(((example *)(0))->b));

Thanks to offsetof (in the header stddef.h), the last line can be rewritten in:

unsigned int offset;
offset = offsetof(example, b);

[via]


Leave a Comment

Your email address will not be published. Required fields are marked *

− 1 = 2