8

I'm using the Code::Blocks IDE with the GNU GCC compiler.

struct test
{
    char a;
    char e;
    char f;
    char b;
    char d;
};

sizeof(test) returns 5.

I read this answer: Why isn't sizeof for a struct equal to the sum of sizeof of each member?

How come there is no padding after the last char, so that sizeof(test) returns 6 or 8? There are a ton more questions I could ask once I add short and int, etc. But I think this question is good for now. Would not padding make it easier for the processor to work with the struct?

Community
  • 1
  • 1
newprogrammer
  • 2,514
  • 2
  • 28
  • 46

2 Answers2

10

The alignment of a char is only 1, so there is no need for the struct to be padded out to meet a larger alignment requirement.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • OK, so let's say my word size is 4 bytes. Let's say I have an array `test stuff[1000]`. My processor reads individual `test`s like `char-char-char-char char-pad-pad-pad`. Does not the array in memory need to be formatted this way as well? – newprogrammer Apr 01 '12 at 20:14
  • @newprogrammer No. It will be 5000 bytes, without padding between members of the array, of members of the struct. – asaelr Apr 01 '12 at 22:30
  • @newprogrammer: There are no "words" in your struct, so the alignment needed for a "word" is irrelevant. – R.. GitHub STOP HELPING ICE Apr 02 '12 at 04:05
  • @newprogrammer: No, it won't. The whole meaning of the alignment of `char` being 1 is that the processor does not expect it to be aligned, so there is no need or reason for it to be padded. – Puppy Apr 02 '12 at 09:30
1

Since at most times you work with one member at time, or pass the address of the struct, the compiler doesn't care to align the whole struct more than the alignment needed for its members. That means that if you assign this struct (or pass it to function), the processor will have to read it member-by-member. (and it will be a little slowly).

asaelr
  • 5,438
  • 1
  • 16
  • 22