Let me explain the concept of padding in structures and
then packed structures by taking an example.
And then let us see why packing is required.
Padding:
struct eg_struct
{
unsigned char abc;
unsigned int xyz;
}
When the structure is declared as above on a 16 bit architecture, the variable abc would be assigned some address. The next address is not assigned to variable xyz, instead one extra byte is added, and then the next address would be assigned to the variable xyz.
In the end, the structure looks something like below:
struct eg_struct
{
unsigned char abc;
unsigned char paddedbytes[1];
unsigned int xyz;
}
Padding makes addresses of member variables easily accessible to the microcontroller.
The disadvantage is extra unnecessary bytes that come into the picture.
Packing:
If same structure is declared using the attribute “packed”, the extra byte will not be added after the variable abc.
Let me give one example where packing is needed:
Consider a microcontroller interfaced with an EEPROM where some structure is being stored.
Imagine a function writing to the EEPROM would look as below:
Write_EEPROM(EEPROM address, Ram address, Byte count);
Now if packing is not done, the extra padded bytes would occupy space in the EEPROM, which is of no use.