How to avoid structure padding using pragma?

We can aviod the structure padding using #pragma.

The default compiler alignment is of 4 bytes. we can use #pragma to change the byte alignment to 1 byte.

For that, do the following steps:

1.    Push the current compiler alignment into the stack.
2.    Set the alignment into 1 byte.
3.    Declare the structure.
4.    Restore the default compiler alignment from the stack.

Example:

#pragma pack(push)  /* push current alignment to stack */
#pragma pack(1)     /* set alignment to 1 byte boundary */
Struct EX
{
Char a;
Short int b;
Char c;
Long d;
};
#pragma pack(pop)   /* restore original alignment from stack */

Thus the structure size is 8 bytes.

Read more about Structure padding


Comments

Leave a Reply