Velocity Reviews > Difference between Unions and Structures...

# Difference between Unions and Structures...

Ravikiran
Guest
Posts: n/a

 11-03-2008
Hi,

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

Thank you..

James Kuyper
Guest
Posts: n/a

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

what is your understanding of what the differences are? If you come
sufficiently close to suggest that you've really tried to do your

MJ_India
Guest
Posts: n/a

 11-03-2008
On Nov 3, 8:09*pm, Ravikiran <(E-Mail Removed)> 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,
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,
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,
In union, as memory allocated is same, change in one _may_ change the
other.