Draw a picture!

char goes at 0 because it can go anywhere

short goes at 2 because it must be on a 2-byte boundary;  it consumes
bytes 2 and 3

char goes at 4 because this is the next byte after the short; it
consumes byte 4; byte 5 is the next byte free

long goes at 8 because this is the next 4-byte boundary after 5

8 + 4 = 12, so the struct takes 12 bytes

On Feb 29, 12:03 pm, Karunakar Reddy <karunakar.r...@gmail.com> wrote:
> how in the second case it is 12?????....can u tell the clear expl..
>
>
>
>
>
>
>
> On Wed, Feb 29, 2012 at 8:39 AM, Gene <gene.ress...@gmail.com> wrote:
> > This depends on the compiler and even on the options you give the
> > compiler.  The C nor C++ standards don't say.
>
> > So the asker of the question hasn't give you enough information.
>
> > If you assume 32-bit x86 gcc with no packing options or pragmas, I
> > think shorts (which are 2 bytes long) are aligned on 2-byte
> > boundaries.  Longs and ints (both 4 bytes long) are on 4-byte
> > boundaries.  Chars (1 byte) can go anywhere.  If you follow these
> > rules, then the first will be laid out:
>
> > Field @ Offset
>
> > a @ 0 // next 3 bytes are padding to reach next 4-byte boundard
> > b @ 4
> > c @ 8 // next 2 bytes are padding
> > d @ 12
>
> > so the struct will be 16 bytes in size (a long is 4 bytes).
>
> > In the second case you'll have
>
> > a @ 0  // next 1 byte are padding
> > b @ 2
> > c @ 4  // next 3 bytes are padding
> > d @ 8
>
> > so the struct will be 12 bytes in size.
>
> > Even if you are using a 64-bit gcc (without the -m32 flag), you'll get
> > an entirely different answer!
>
> > On Feb 29, 11:13 am, Decipher <ankurseth...@gmail.com> wrote:
> > > I need some help in understanding how padding works ??
> > > Please answer the following questions with proper explanations..
>
> > > struct mystruct1
> > > {
> > >   char a;
> > >   int b;
> > >   short c;
> > >   long d;
>
> > > };
>
> > > struct mystruct2
> > > {
> > >   char a;
> > >   short b;
> > >   char c;
> > >   long d;
>
> > > };
>
> > > What's the sizeof above 2 structures and why ??
>
> > --
> > You received this message because you are subscribed to the Google Groups
> > "Algorithm Geeks" group.
> > To post to this group, send email to algogeeks@googlegroups.com.
> > To unsubscribe from this group, send email to
> > algogeeks+unsubscr...@googlegroups.com.
> > For more options, visit this group at
> >http://groups.google.com/group/algogeeks?hl=en.

-- 
You received this message because you are subscribed to the Google Groups 
"Algorithm Geeks" group.
To post to this group, send email to algogeeks@googlegroups.com.
To unsubscribe from this group, send email to 
algogeeks+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/algogeeks?hl=en.

Reply via email to