Skip to main content
gamedev.net
🔒 Locked

sizeof struct

Started by peter86 3 replies 650+ views
Original Post
peter86
peter86
I came across a confusing phenomenon; why is sizeof(myStruct) == 8? struct myStruct { unsigned long numberOne; unsigned short numberTwo; }; If I put the pragmas below around it, the size will be 6, why? When do I need to use this "workaround"? And what does this pragma do? #pragma pack(push, 1) /* ... */ #pragma pack( pop )
Zakwayda
Zakwayda
I would guess the compiler is padding to align the data to 4-byte increments, and that the pragma overides that by instructing the compiler to pack the data together contiguously.
Gink
Gink
it's 8 because it's more effecient for 32 bit cpus to access 4 bytes at a time than 2.
MaulingMonkey
MaulingMonkey
This extra padding (the extra two bytes which are confusing you) is provided to ensure numberOne is allways on a four byte boundry, which allows for more efficient access. You should never need to use this "workaround", but people often (mis)use it to read files by reading in a big chunk of data and then casting a pointer to that data to a pointer to a specific structure.

The pragma sets (pushes), and then unsets (pops), the "pack" option which controls how to align data - pack( push , 1 ) sets this to 1-byte boundries. Depending on your compiler, I believe the default may be something like 8 (meaning the compiler will pad so that any 8-byte type (e.g. __uint64 or similar) will be aligned on an 8-byte boundry (e.g. the address will look like either: 0x_______0 or 0x_______8).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.