Like Tree3Likes
  • 3 Post By iMalc

Size of Union

This is a discussion on Size of Union within the C Programming forums, part of the General Programming Boards category; Hello, In the following union, the size of the union variable displayed using sizeof operator is 52. If I comment ...

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    1

    Size of Union

    Hello,
    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)

    Code:
    union myUnion
    {
        int var1;
        char char1;
        //double mydouble1;
        char string1[50];
    };

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

    Tim S.
    "Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to produce bigger and better idiots. So far, the Universe is winning." Rick Cook

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,302
    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).
    Salem, Prelude and Tanu like this.
    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, 01: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, 02: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


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21