c - sizeof char array inside an union is not printing correctly -


this question has answer here:

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

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -