+ 4

C - While sizeof of this struct is 8?

#include <stdio.h> typedef struct { int bit1 : 1; int bit2 : 2; int bit30 : 30; } bits; int main() { printf("%d", sizeof(bits)); return 0; } I expect it to be 4, but when sum of integers exceeds 32, it becomes 8. Why?

16th Aug 2019, 8:54 AM
Paolo De Nictolis
Paolo De Nictolis - avatar
3 odpowiedzi
+ 4
Int can have 32 bits - 4 bytes. As number of bits used in ur struct is 33 bits. Next possible size is 2 ints = 8 bytes. Bit fields in struct can have only int has members.
16th Aug 2019, 9:08 AM
Kuri
Kuri - avatar
+ 2
I think that for an integer variable with a value from 0 to 29 4 bits of memory are allocated, from 30 to 32 8 bits are allocated, 33 already requires the type of the variable long - for which 16 bits are already allocated, that is: "long long bit33: 33;". Я так думаю что для переменной типа integer со значением от 0 до 29 выделяется 4 бита памяти, от 30 до 32 выделяется 8 бит, от 33 требуется уже тип переменной long - для которой уже выделяется 16 бит, то есть: "long long bit33: 33;". P.S: "29 = 0b11101; 30 = 0b11110; 31 = 0b11111; 32 = 0b100000; 33 = 0b100001;".
16th Aug 2019, 10:27 AM
Solo
Solo - avatar
0
Maybe it's a 64bit integer
16th Aug 2019, 7:32 PM
0x4d616e75
0x4d616e75 - avatar