Thread: Size of Union

  1. #1
    Registered User
    Join Date
    Jan 2013

    Size of Union

    In the following union, the size of the union variable displayed using sizeof operator is 52. If I comment the integer, the size is 50. If I include double variable also, the size is 56. What is the reason for this? The size should only be 50 right (size of Largest member)

    union myUnion
        int var1;
        char char1;
        //double mydouble1;
        char string1[50];

  2. #2
    Registered User
    Join Date
    May 2009
    My guess is alignment issues might be causing greater size; possibly because of a compiler bug or by design.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    New Zealand
    It's adding padding so that if you had an array of these unions, then each foo[i].var1 would be aligned to a 4 byte boundary (the size of an int here).
    Or with a double, the padding ensures that each foo[i].mydouble1 would be aligned to a 8 byte boundary (the size of a double).
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. size of union without using sizeof operator
    By shruthi in forum C Programming
    Replies: 20
    Last Post: 08-31-2012, 06:34 AM
  2. Union of a set
    By bman900 in forum C Programming
    Replies: 5
    Last Post: 11-07-2010, 02:46 AM
  3. Size of the UNION
    By BlackOps in forum C Programming
    Replies: 14
    Last Post: 07-11-2009, 04:29 PM
  4. Finding Words in a array[size][size]
    By ^DJ_Link^ in forum C Programming
    Replies: 8
    Last Post: 03-08-2006, 03:51 PM
  5. if union could...
    By black in forum C++ Programming
    Replies: 8
    Last Post: 06-13-2002, 08:34 AM

Tags for this Thread