c - sizeof char array inside an union is not printing correctly -
this question has answer here:
- sizeof union in c/c++ 8 answers
union u { int a; float b; char c[10]; }; int main() { union u abc; printf("\n%d",sizeof(abc)); }
output: 12 expect output 10.sizeof(char) 1. 10 expect 10. can explain me why 12.
this because @ least 1 between float
or int
data type has 4 bytes alignment requirement. struct
gets 2 bytes of padding (so sizeof(struct u) % 4 == 0
).
you can use __attribute__((packed))
or similar features if compiler supports them avoid padding it's not convenient unless have preexisting data conform with. think fact array of packed struct u
elements have unaligned float
/int
members.
Comments
Post a Comment