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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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 tests like char-char-char-char char-pad-pad-pad. Does not the array in memory need to be formatted this way as well?
@newprogrammer No. It will be 5000 bytes, without padding between members of the array, of members of the struct.
@newprogrammer: There are no "words" in your struct, so the alignment needed for a "word" is irrelevant.
@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.
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).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.