-6

Code:

#include <stdio.h> 

int main()
{
    union sample
    {
        int   m[2];
        float n[3];
        char ch[18];
    }u;

    printf("The size of union = %d\n", sizeof(u));

    return 0;
}

I was expecting 18 as output Here it is providing unexpected output.

timrau
  • 22,578
  • 4
  • 51
  • 64
deepak jha
  • 19
  • 1
  • 2
    What output did you get and what output did you expect? Please read this: [ask] – Jabberwocky Oct 09 '19 at 08:50
  • 1
    Possible duplicate of [Union element alignment](https://stackoverflow.com/questions/891471/union-element-alignment) – Blaze Oct 09 '19 at 08:50
  • 1
    @Fredrik he probably gets 20 as output because int and float likely have size of 4 and it's aligning it to be a multiple of that. – Blaze Oct 09 '19 at 08:52

1 Answers1

0

This is because of padding and alignment.

A union may have padding at the end to ensure proper alignment of its fields when the union is part of an array.

In this case, there is a field with type array of int and another of type array of float. These types are most likely 4 bytes in size, so the union’s size needs to be a multiple of 4. So instead of 18 the size will be 20 to satisfy that alignment.

dbush
  • 205,898
  • 23
  • 218
  • 273