Getting the offset of a member in a struct

Submitted by Eus
on May 18, 2008 - 8:02am
struct aligned_struct
{
	char a [5];
	int b;
};

It is tempting to say that b is located at the 6th byte from the beginning of the struct because a has already occupied the first 5 bytes. But, actually b is located at the 9th byte from the beginning of the struct because b is aligned at every 4 bytes. Therefore, to know exactly the offset of a member of a struct (i.e., at what n-th byte from the beginning of the struct the member is located), simply use the following technique that I found in Linux kernel 2.6.21.5 source code file in include/linux/stddef.h:

((size_t) &(((struct aligned_struct *)0)->b))

This technique is interesting because it turned out that you can treat a constant as a memory address.

In general as written in the source code file:

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

Archive: All about C Programming

alignment in data structures

on
May 18, 2008 - 11:50am

Alignment/compiler-generated-padding of data structures/its members are the very important hardware questions and actually issues for system programmers.

http://en.wikipedia.org/wiki/Data_structure_alignment

E.g. Daniel Drake is author of the driver for _wireless_ chip[1]. After recognizing his ignorance(much latter), he wrote this[0]:

[0] http://lwn.net/Articles/260456/
[1] http://lxr.linux.no/linux/drivers/net/wireless/zd1211rw/

IOW just look at TCP/IP data structures and USB. Data structures, that are clueless about alignment, is one of the many problems of x86 hegemony.

Now I understand

on
May 12, 2009 - 8:34pm

Hi Ho!

Data structures, that are clueless about alignment, is one of the many problems of x86 hegemony.

Finally I understand what olecom means after I know the fact that x86 permits unaligned memory access (it will never SEGFAULT) [http://kerneltrap.org/node/17044].

Best regards,
Eus (FSF member #4445)

In this digital era, where computing technology is pervasive,
your freedom depends on the software controlling those computing devices.

Join free software movement today!
It is free as in freedom, not as in free beer!

Join: http://www.fsf.org/jf?referrer=4445

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.