Recursive Complexity

Thoughts and musings of a programmer and wanna be entrepreneur

Archive for April 2013

Finding the offset of a field inside a structure in C

leave a comment »

How do you find the offset of a field inside a structure from the beginning of the structure in C given only the structure name and the field name.

Below is the code.


#define offset_of(a, b) &(((a*)0)->b)

struct mystruct {
    int a;
    long b;
    int c;
};

void main()
{
    printf("%llu\n", offset_of(struct mystruct, c));
}

//output on a 64 bit machine

8

What we are doing here is typecasting 0 to be of type mystruct pointer which sets the beginning of the structure as 0 and then return the address of ‘c’ which should get us the offset. This is possible because of the ability to typecast variables to required types which is one of the strengths of C.

Advertisements

Written by Vivek S

April 18, 2013 at 8:43 am

Posted in Tech

Tagged with ,

TED Blog

The TED Blog shares interesting news about TED, TED Talks video, the TED Prize and more.