Why the concept of padding is added only when there are multiple members of a structure and why is it not included when there is a single basic data type member ?
if we consider on a 32bit machine
struct
{
char a;
} Y;
There is no padding and sizeof Y comes to 1 byte .
If we consider this structure
struct
{
char a;
int b;
} X;
Sizeof X will be 8bytes .
My question is
Why was padding adding in the second case ? If it is for efficient access by the machine which normally reads data in blocks of multiples of 4bytes then why was there no padding in the first case ?
Padding is added in the second case because, on your machine, an
intis aligned to 4 bytes. So it has to reside at an address that is divisible to 4.If no padding is added, the
intmember starts at address0x05, which is wrong. With 3 added padding bytes:Now the
intis at0x08, which is OK.