Monday, November 2, 2009

CODIES 1.1

Point out the difference between the two structure declarations:

struct one
{
char charA;
short shortA;
char charB;
long longA;
char charC;
}

struct two
{
long longA;
char charA,charB,charC;
short shortA;
}

A good detailed explanation wins a treat !!!

5 comments:

  1. the difference is no. of padding bytes.

    char variables are 1 byte aligned and so they can appear at any byte boundary, while short which is 2 byte aligned can appear at byte boundary which is multiple of two.
    similarly, long will appear at byte boundary which is multiple of four.

    To cope up with this padding bytes will be added.

    in struct two:- one padding byte seems to appear before shortA.

    in struct one:- one padding will appear before shortA & 3 padding byte will appear before longA.

    ReplyDelete
  2. In the first ex., shortA will always gets a lower address than that of longA. In the 2nd ex., vice versa. Similarl rule applies for the char variables. Am I right or not...

    ReplyDelete
  3. Detailed Exact Answer:difference of 4 bytes!!

    IN ONE:
    charA 1
    {padding field} 1
    shortA 2
    charB 1
    {padding field} 3
    longA 4
    charC 1
    {padding field} 3 // see note1 below
    __________________
    sizeof(one) 16 //total size rqd by one
    ===================

    note1: Here the padding field of '3' must be inserted to make the sizeof(one) to be the multiple of 4 as it contains 'long' as a str member. This type of padding is called "trailing padding" :). The other padding types are internal padding(in b/w the member as b4 shortA and longA here) and leading padding(which is not allowed in C).

    IN TWO:

    longA 4
    charA 1
    charB 1
    charC 1
    {padding field} 1
    shortA 2
    {padding field} 2 //similar to note1
    ------------------
    sizeof(two) 12 only!!
    ==================

    Acc to C stnrds, w/i an obj, str members have addresses that increase in the order in which they are declared. So, Compiler will not rearrange the str members in an effective way.(my 1st ans was based on this funda :) )
    Also, this str packing may (!sure)dependent on the compiler.

    Prakhar, I hope I will get the treat... :)

    Anyway, pls continue posting the new coding challenges....

    ReplyDelete
  4. @ Guru: Nice explanation man !!!
    Keep sharing ur knowledge, lemme appreciate ur description of various types of padding and also the details abt working of compiler.....

    @Prabhat:
    Very Good explanation too... short simple and to the point...

    ReplyDelete