> -----Original Message-----
> From: Vishal Jain [mailto:vishal.jain@globaledgesoft.com] 
> Sent: Monday, April 18, 2005 1:22 PM
> To: Vijay Zanvar (WT01 - TELECOM SOLUTIONS)
> Subject: Re: 
> 
> 
> >  59. What is structure padding? Explanation 
> > .
> 
> Vijay ,
> Continuing the discussion on cell padding ...
> i tried to run these 3 programs...
> 
> They are as follows:
> _PRG 1 _
> 
> >
> >     struct
> >     {
> >         int  c;
> >         char d;
> >         int p;
> >     } v1;
> >
> >     main()
> >     {
> >         int l;        
> >         l = sizeof(v1);    
> >         printf("\n l = % d",l);        
> >     }
> 
> It seems to be Ok...The output is as expected ....
> The size is as expected.
> 

OK.

> _PRG 2 _
> But if i give the structure variable as follows :
> struct
>     {
>         int  c;
>         char i;
>         char d;
>         int p;
>     } v1;
> 
> main()
>     {
>         int l;        
>         l = sizeof(v1);    
>         printf("\n l = % d",l);        
>     }
> 
> I was expecting the size as 16 but i got 12 as size.
> I feel for 'char i 4' bytes will be allocated and another 4
> for 'char d '.


> For ints it will be 4 + 4 again.
> Making a total of 16( Expected )
> 

i and d go into the same storage.

> But the total size comes as 12 ...
> Why this difference ??
> 

If you replace char by short, the size will still be 12.  Because,
i and d are of same types and less than the size of the memory word,
which is 4 bytes.  

So the simple rule is: if two (or more) members of same type are 
successive members, then they go to the same memory storage cell, 
provided that their combined size is less than or equal to that of 
the storage cell.

> _PRG 3 _
> 
> Now if in interchange order of  'char d' and 'int p ' ie the 
> structure 
> is now
> struct
>     {
>         int  c;
>         char i;
>         int p;
>         char d;
>     } v1;
> 
> main()
>     {
>         int l;        
>         l = sizeof(v1);    
>         printf("\n l = % d",l);        
>     }
> Now if i check the size of(v1) i get the size as 16 which is 
> expected ...
> 
> Explain ??( I hope my description is clear enough )
> 

Compiler can do bit padding, but cannot reorder the structure members.
You know from the link I gave you that there will be padding after
i and d to achieve alignement, so they reside in different memory cells.
Hence, the size is 16 bytes.

So you, as a programmer, should write the structure accordingly if 
efficiency is desired.  But sometimes we can't do that, because the
structure is written to conform an external device; for example,
register definitions, etc.

    Source: geocities.com/vijoeyz/faq/c

               ( geocities.com/vijoeyz/faq)                   ( geocities.com/vijoeyz)