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)); }

9/25/2019 1:32:20 PM

YaSh

6 Answers

New Answer

+2

YaSh Yes all data can fit in 16 bits, but compiler will not rearrange the order of declaration of bit fields first 3 fits in 1 byte(size 1,2,3) 2 bit remains next 4 bits can't go in so next byte is allocated and it consumes 4 bits, remaining 4 bits, next 6 bits can't go in so allocate one more byte and fit 6 bits, so total bytes allocated is 3 bytes. To get 2 bytes rearrange the order as unsigned char :6; unsigned char b:2; unsigned char c:4; unsigned char d:3; unsigned char e:1;

+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.

+1

YaSh Bit field implementation is compiler specific so is their packing. If you make a,b,c,d as unsigned char but leave the last unnamed field as unsigned, then sololearn compiler gives you the size as 8, Cxxdroid offline mobile compiler gives you size as 4. Online C compilers i checked, both gcc and clang gave me 3 bytes. If you make last unnamed field too as unsigned char, then all compilers gave me size as 3. The point is their implementation is compiler specific and so is their packing. https://stackoverflow.com/questions/17723604/bitfields-why-implementation-specific

0

Type int, so 4 bytes.

0

Well then why it is giving 3 bytes when you specify the type of a,b,c,d as unsigned char??

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..