-1
union u
{
    int a;
    float b;
    char c[10];
};
int main()
{
    union u abc;
    printf("\n%d",sizeof(abc));
}

Output: 12 I expect the output to be 10.sizeof(char) is 1. So for 10 i expect it to be 10. Can someone explain me why do we get 12.

Manisha P
  • 111
  • 2
  • 9

1 Answers1

2

This because probably at least one between float or int data type has 4 bytes alignment requirement. So the struct gets 2 bytes of padding (so that sizeof(struct u) % 4 == 0).

You can use __attribute__((packed)) or similar features if your compiler supports them to avoid padding but it's not convenient unless you have preexisting data to conform with. Think about the fact that an array of packed struct u elements will have unaligned float/int members.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • "This because float (and int) have 4 bytes alignment requirement." --> Could be just one of the two have the requirement especially with a 16-bit `int`. – chux - Reinstate Monica Apr 14 '17 at 17:27
  • 1
    @chux: yes, on most non embedded platforms both will mostly be 4 bytes, on embedded platforms it really depends. I'm unsure about half precision floating, surely used in computer graphics but no clues which embedded architectures could use it as a direct replacement for `float`. – Jack Apr 14 '17 at 17:31