I want to be able to find the size of the individual members in a struct. For example
struct A {
int a0;
char a1;
}
Now sizeof(A) is 8, but let's assume I am writing a function that will print the alignment of A as shown below where "aa" represents the padding.
data A:
0x00: 00 00 00 00
0x04: 00 aa aa aa
*-------------------------
size: 8 padding: 3
In order for me to calculate padding, I need to know the size of each individual members of a struct. So my question is how can I access to individual members of a given struct.
Also, let me know if there is another way to find the number of padding.
To calculate the padding of a structure, you need to know the offset of the last member, and the size:
Concisely, if type
Thas a memberlastwhich is of typeU, the padding size is:To calculate the total amount of padding in a structure, if that is what this question is about, I would use a GCC extension: declare the same structure twice (perhaps with the help of a macro), once without the
packedattribute and once with. Then subtract their sizes.Here is a complete, working sample:
For the above structure, it outputs 6. This corresponds to the 3 bytes of padding after
anecessary for the four-byte alignment ofband at the end of the structure, necessary for the alignment ofbif the structure is used as an array member.The
packedattribute defeats all padding, and so the difference between the packed and unpacked structure gives us the total amount of padding.