Question

Say I have a structure:

struct myStruct
{
    int a;
    short b;
    char c;
};

In Windows, MSDN states that int takes 4 bytes, short takes 2 bytes and char takes 1 byte. This totals up to 7 bytes.

I understand that most compilers will pad structures with an unspecified number of bytes to improve alignment. So, when I execute this program,

#include <stdio.h>

int main(void) {
    printf("%d\n", sizeof(struct myStruct));
    return 0;
}

I get an output of 8. This means 1 byte was padded.

Is there any way I can maintainably determine struct sizes in code (short of adding up individual sizeofs)?

I ask this because later, if I need to change my structure to include about fifteen elements more and if I add five more structures, all my struct sizeofs will change causing things to get messy.

Was it helpful?

Solution

You can enforce it:

#define C_ASSERT(expr) extern char CAssertExtern[(expr)?1:-1]

C_ASSERT(sizeof(struct myStruct) == 7); // or 8, whichever you want

Whenever the size diverges from 7, the code will simply cease to compile.

You can do similar things to enforce offsets of structure members. You'll need the offsetof() macro for that.

OTHER TIPS

You can try pragma pack. It helps maintaining an alignment and has many flexibility. check this http://publib.boulder.ibm.com/infocenter/comphelp/v101v121/index.jsp?topic=/com.ibm.xlcpp101.aix.doc/compiler_ref/pragma_pack.html

Update: just now saw your comment, perhaps pack is not your solution then

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top