Find The Offset Of An Element In A Structure In C- offsetof()
Tuesday, May 5th, 2009Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email
First of all, I apologize for the decreased frequency of updates. We have been quite busy with our offline lives and primary livelihoods lately keeping us away from posting much. But we intend to not let it remain like this for much longer. I’m posting a short article today about something that almost everyone of us has had to do at some point of time, i.e., to find the offset (or relative position in bytes) of an element in a structure. Let’s take the following structure as an example:
struct { char a; int b; char c; }example;
Now, if I were to ask you to find out the element b’s offset in the above structure, you won’t probably be able to answer with complete confidence unless I tell you the compiler you are working with and whether packing has been turned on or not. The easiest way to find it out is to use a small snippet of code to do it for us and that always works. e.g.
struct example s1; unsigned int offset; offset = (unsigned int)&s1.b - (unsigned int)&s1;
The above snippet will work, but not always (Hint). Many people use a much simplified form, which does not involve any pointer arithmetic:
unsigned int offset; offset = (unsigned int)(&(((example *)(0))->b));
The above code is much simpler/faster but again, it might not be portable. So, what is the best method to do this portably. It’s quite simple really, just use the “offsetof” macro provided by any ANSI-C compliant compiler. It is present in stddef.h and can be used in the following way:
size_t offset; offset = offsetof(example, b);
If you noticed, offsetof() also presents another advantage to you like the 2nd method, i.e., it does not require an extra structure to be defined. In fact, this macro is defined in forms similar to our method 2 but the benefit is that it ensures portability for your code.
© Safer Code | Find The Offset Of An Element In A Structure In C- offsetof()
|
Liked this post? Get FREE Updates Subscribe to RSS feed |