[Tutor] struct.calcsize curiosity...

Greg Graham GGraham at cistercian.org
Tue Mar 25 22:49:03 CET 2008


Lawrence Wang wrote:
> >>> struct.calcsize('hq')
> 12
> >>> struct.calcsize('qh')
> 10
>
> why is this? is it platform-dependent? i'm on mac os x.

This has to do with data alignment and is platform-dependent. Are you on
a PowerPC Macintosh? On my Intel Windows XP box, I get the following:

In [3]: struct.calcsize('hq')
Out[3]: 16

In [4]: struct.calcsize('qh')
Out[4]: 10


I suspect on your computer, the elements of the struct have to be
aligned on a 4 byte boundary. In the case of 'hq', the h takes 2 bytes,
and the q takes 8 bytes. However, the q must start on a 4 byte boundary,
so 2 bytes are wasted as padding between the h and the q. In the second
example, because the q is first and takes 8 bytes, the h begins on a 4
byte boundary, so no padding is used. Note however if you had an array
of 'qh' structs, I would expect there to still be 2 bytes of padding
between each array member.

On my machine, it seems to align on 8 byte boundaries, so in the 'hq'
case, I'm wasting 6 bytes for padding between the h and the q.

Greg
 


More information about the Tutor mailing list