Home > Enterprise >  How exactly structure packing and padding work?
How exactly structure packing and padding work?

Time:11-16

How exactly structs are packed and padded in c ? The standard does not says anything about how it should be done (as far as I know) and compilers can do whatever they want. But there are tutorials showing how to efficiently pack structs with known rules (for example that every variable needs to be on address that is multiple of its size and if end of previous variable is not multiple, then padding will be inserted), and with these rules we can pack structs by hand in source. What is it finally? We know in what way structs will be packed on modern machines (for example PCs) or it is just idea that can be right, but it is not good to take it for granted?

CodePudding user response:

How exactly structs are packed and padded in c ?

Short answer: In such way that alignment requirements are satisfied.

The standard does not says anything about how it should be done (as far as I know) and compilers can do whatever they want.

Within bounds of the alignment requirements, this is indeed correct. This is also an answer to your question.

  • Related