0

Possible Duplicate:
offsetof at compile time

How can I find the offset of a member within a struct in C? For example, how can I find the offset of t in this struct:

struct test
{
  int a;
  int b;
  struct test* t;      
  int c;
};
Community
  • 1
  • 1
Prabagaran
  • 903
  • 1
  • 9
  • 17

1 Answers1

4

Use the offsetof() macro from stddef.h: offsetof(struct test, t). (ideone example)

cdhowie
  • 158,093
  • 24
  • 286
  • 300
  • #define offset_of(TYPE , MEMBER) ((size_t) &((TYPE*)0)->MEMBER) It seems like dereferencing a null pointer. How does this helps in finding the offset. – Prabagaran Jun 07 '12 at 19:03
  • It does, but the outer `&` (address-of) operator effectively "undoes" the dereference. The overall expression asks "what address would MEMBER be at if there was a TYPE instance at memory location 0?" – cdhowie Jun 07 '12 at 19:54