newprogrammer
newprogrammer

Reputation: 2604

C/C++: Packing or padding data in a struct

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?

Upvotes: 8

Views: 366

Answers (2)

asaelr
asaelr

Reputation: 5456

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).

Upvotes: 1

Puppy
Puppy

Reputation: 146910

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.

Upvotes: 10

Related Questions