P.C.
P.C.

Reputation: 649

How do I calculate the size and layout of this particular struct?

The structure is,

struct { 
    char a;
    short b; 
    short c; 
    short d; 
    char e;
} s1;

size of short is given as 2 bytes size of char is given as 1 bytes It is a 32-bit LITTLE ENDIAN processor

According to me, the answer should be:

1000    a[0]
1001    offset
1002    b[0]
1003    b[1]
1004    c[0]
1005    c[1]
1006    d[0]
1007    d[1]
1008    e[0]

size of S1 = 9 bytes​

but according to the solution, the size of S1 is supposed to be 10 bytes

Upvotes: 1

Views: 41

Answers (2)

user1666959
user1666959

Reputation: 1855

The C Standard says (sorry, not at my computer, so no quote): structs are aligned to the alignment of the largest (base type) member. Your largest member field is a short, 2 bytes, so the first element 'a' is aligned at an even address. 'a' takes up 1 byte. 'b' has to be aligned again at an even address, so one byte gets wasted. The last element of your struct 'e' is also one byte, and the byte following that is likely to be wasted, but that doesn't have to show up in the size of the struct. If put 'a' to the end, ie rearrange the members, you are likely to find the size of your struct to be 8 bytes..which is as good as it gets.

Upvotes: 1

user3344003
user3344003

Reputation: 21710

The answer here is that it is that the layout of the structure is entirely up to the compiler.

10 is likely to be the most common size of this structure.

The reason for the padding is that, if there is an array, it will keep all the members properly aligned. If the size were 9, every other array element would have misaligned structure members.

Unaligned did accesses are not permitted on some systems. On most systems, they cause the processor to use extra cycles to access the data.

A compiler could allocate 4 bytes for each element in such a structure.

Upvotes: 1

Related Questions