0

So, there are two 'almost' similar structure in 'C' code

1st:

struct P1 {
    int i;
    char c;
    char d;
    int e;
};
printf("3. size of struct is, %d\n", sizeof(P1));

Gives a console Output: 3. size of struct is, 12

2nd:

struct P2 {
    int i;
    char c;
    int e;
    char d;
};
printf("4. size of struct is, %d\n", sizeof(P2));

Gives the console output: 4. size of struct is, 16

Can anyone explain the discrepancy? (Even though both the struct have 2 int and two char) Thanks in advance!

user3204053
  • 79
  • 1
  • 7
  • 2
    How is the question related to C++? (ok, the answer happens to be the same for both languages in this case) – eerorika Oct 22 '15 at 07:55
  • 2
    Pls see this http://stackoverflow.com/questions/1841863/size-of-a-structure-in-c – throwit Oct 22 '15 at 07:56
  • I would appreciate if you could see my two structures and answer the discrepancy as asked in the question, I think I understand the padding and memory alignment concept a bit, if I can get an answer for my particular question, I may get better understanding @ F. Ju – user3204053 Oct 22 '15 at 08:11
  • 1
    @user3204053 in the second one you have int (4byte) + char(1byte + 3 padding) + int(4byte) + char(1byte+ 3 padding) which equals 16. In the first you have int(4byte) + 2x (char 2byte + 2 padding) + int (4 byte) which equals 12. – Magisch Oct 22 '15 at 09:24
  • Thius is homework isn't it? Yout don't want any hints or links, you WANT YOUR QUESTION ANSWERED IN FULL HERE for copypasta. – Martin James Oct 22 '15 at 10:16

0 Answers0