Recursive Complexity

Thoughts and musings of a programmer and wanna be entrepreneur

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 ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

TED Blog

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

%d bloggers like this: