Difference between Unions and Structures...

Discussion in 'C Programming' started by Ravikiran, Nov 3, 2008.

  1. Ravikiran

    Ravikiran Guest

    Hi,

    I want know the differences between Unions and Structures in C
    programming.

    Thank you..
     
    Ravikiran, Nov 3, 2008
    #1
    1. Advertising

  2. Ravikiran

    James Kuyper Guest

    Ravikiran wrote:
    > Hi,
    >
    > I want know the differences between Unions and Structures in C
    > programming.


    This sounds like a homework problem. After having read your textbook,
    what is your understanding of what the differences are? If you come
    sufficiently close to suggest that you've really tried to do your
    homework, we'll be glad to help you with needed corrections.
     
    James Kuyper, Nov 3, 2008
    #2
    1. Advertising

  3. Ravikiran

    MJ_India Guest

    On Nov 3, 8:09 pm, Ravikiran <> wrote:
    > I want know the differences between Unions and Structures in C
    > programming.

    struct STest
    {
    type1 A;
    type2 B;
    type3 C;
    };
    struct STest st;
    You can visualize it in memory as,
    Address Data
    A0+---+
    | A |
    A1+---+
    | B |
    A3+---+
    | C |
    A4+---+

    In actual scenario there might be some padding after A, B etc.
    A1 >= A0 + sizeof(type1) (>= because there may be a few byte padding)
    A2 >= A1 + sizeof(type1)
    ....
    A4 = A0 + sizeof(STest)
    sizeof(STest) >= sizeof(type1) + sizeof(type2) + sizeof(type3)

    Union UTest
    {
    type1 A;
    type2 B;
    type3 C;
    };
    union UTest ut;
    You can visualize it in memory as,
    Address Data
    A0+---+---+---+
    | A | B | C |
    A1+---+---+---+

    A1 >= A0 + max(sizeof(type1), sizeof(type2), sizeof(type3))

    In structure if you change the contents of A, B and C are unaffected,
    as the address are different.
    In union, as memory allocated is same, change in one _may_ change the
    other.
     
    MJ_India, Nov 3, 2008
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. jakk
    Replies:
    4
    Views:
    12,228
  2. Neil Zanella
    Replies:
    9
    Views:
    418
    Jeffrey D. Smith
    Oct 16, 2003
  3. Alfonso Morra
    Replies:
    11
    Views:
    720
    Emmanuel Delahaye
    Sep 24, 2005
  4. Jason Curl

    Unions and structures implementation in C

    Jason Curl, Oct 12, 2005, in forum: C Programming
    Replies:
    4
    Views:
    803
    Default User
    Oct 12, 2005
  5. Ravikiran

    Difference between Unions and Structures...

    Ravikiran, Nov 3, 2008, in forum: C Programming
    Replies:
    7
    Views:
    624
    CBFalconer
    Nov 3, 2008
Loading...

Share This Page