8 Dec 2013 rkrishnan   » (Journeyer)

Neat hack to find offsets of C Structure members

Posted on November 13, 2013 by rkrishnan

Suppose we have a C structure with some elements like this:

  struct T {
    int foo;
    long bar;
    float baz;

C, being a portable assembler, arranges these data sequentially in the memory and aligns them appropriately. What if you want to find the offsets from the base of each of the element?

This macro does the trick. There are other more explicit ways to calculate it. But I found this macro very neat.

    #define OFFSET(x, y)  &((x *)0)->y

We use it this way:

    int offset;
  offset = OFFSET(struct T, bar);

How does this work? The idea is based on the fact that if the structure is put in memory starting from address 0, a pointer to the element inside the structure is also the same as the offset, since the base address is 0. So, we cast an integer (0 in this case) to a pointer pointing to the structure and just find the offset to the element whose offset we are interested in. The address of that element should be the same as offset, as the structure is assumed to be laid in the memory starting at address 0. That’s it.

The linux kernel defines a similar macro in the include/linux/stddef.h called offsetof:

  #ifdef __compiler_offsetof
#define offsetof(TYPE,MEMBER) __compiler_offsetof(TYPE,MEMBER)
#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)

Syndicated 2013-11-13 00:00:00 from Ramakrishnan Muthukrishnan

Latest blog entries     Older blog entries

New Advogato Features

New HTML Parser: The long-awaited libxml2 based HTML parser code is live. It needs further work but already handles most markup better than the original parser.

Keep up with the latest Advogato features by reading the Advogato status blog.

If you're a C programmer with some spare time, take a look at the mod_virgule project page and help us with one of the tasks on the ToDo list!