I have defined this struct:
typedef struct { char A:3; char B:3; char C:3; char D:3; char E:3; } col;
The sizeof(col)
give me the output of 3, but shouldn't it be 2? If I comment just one element, the sizeof
is 2. I don't understand why: five element of 3 bits are equal to 15 bits, and that's less than 2 bytes.
Is there an "internal size" in defining a structure like this one? I just need a clarification, because from my notion of the language so far, I expected a size of 2 byte, not 3.
A struct that is aligned 4 will always be a multiple of 4 bytes even if the size of its members would be something that's not a multiple of 4 bytes.
The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.
In C language, sizeof() operator is used to calculate the size of structure, variables, pointers or data types, data types could be pre-defined or user-defined. Using the sizeof() operator we can calculate the size of the structure straightforward to pass it as a parameter.
In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes. Structure padding is used to save number of CPU cycles. Let's see what compiler is giving using the sizeof() operator.
Because you are using char
as the underlying type for your fields, the compiler tries to group bits by bytes, and since it cannot put more than eight bits in each byte, it can only store two fields per byte.
The total sum of bits your struct uses is 15, so the ideal size to fit that much data would be a short
.
#include <stdio.h> typedef struct { char A:3; char B:3; char C:3; char D:3; char E:3; } col; typedef struct { short A:3; short B:3; short C:3; short D:3; short E:3; } col2; int main(){ printf("size of col: %lu\n", sizeof(col)); printf("size of col2: %lu\n", sizeof(col2)); }
The above code (for a 64-bit platform like mine) will indeed yield 2
for the second struct. For anything larger than a short
, the struct will fill no more than one element of the used type, so - for that same platform - the struct will end up with size four for int
, eight for long
, etc.
Because you can't have a bit packet field that spans across the minimum alignment boundary (which is 1 byte) so they'll probably get packed like
byte 1 A : 3 B : 3 padding : 2 byte 2 C : 3 D : 3 padding : 2 byte 3 E : 3 padding : 5
(the orders of field/padding inside the same byte is not intentional, it's just to give you the idea, since the compiler could laid them down how it prefers)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With