Why is the sizeof(v) showing 4 bytes?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why is the sizeof(v) showing 4 bytes??

#include<stdio.h> int main() { static struct my_struct{ unsigned a:1; unsigned b:2; unsigned c:3; unsigned d:4; unsigned :6; }v={1,2,7,12}; printf("%d %d %d %d",v.a,v.b,v.c,v.d); printf("\nSize-%d bytes",sizeof (v)); }

25th Sep 2019, 1:32 PM
YaSh
YaSh - avatar
4 Answers
+ 1
Alignment of my_struct is 4 bytes because of unsigned int and the accumulated bits only add up to 16 bits == 2 bytes so the size has to be 4 bytes. As for the 3 bytes with unsigned chars, alignof(unsigned char) == 1, depending on how the compiler packs your structs and how the members are ordered it could be 2 or 3 bytes https://www.geeksforgeeks.org/is-sizeof-for-a-struct-equal-to-the-sum-of-sizeof-of-each-member/ is an example.
25th Sep 2019, 3:30 PM
jtrh
jtrh - avatar
0
Type int, so 4 bytes.
25th Sep 2019, 1:35 PM
KfirWe
KfirWe - avatar
0
Well then why it is giving 3 bytes when you specify the type of a,b,c,d as unsigned char??
25th Sep 2019, 1:44 PM
YaSh
YaSh - avatar
0
Brother i am still confused about unsigned char.. Why is it giving 3 bytes and not 2 bytes.. Since we only have 16 bits in total.. so 2 bytes is enough for holding every element.. considering all elements including last as unsigned char..
25th Sep 2019, 4:09 PM
YaSh
YaSh - avatar