Possible Duplicate:
Difference between a Structure and a Union in C
I could understand what a struct means. But, i am bit confused with the difference between union and struct. Union is like a share of memory. What exactly it means.?
Possible Duplicate:
Difference between a Structure and a Union in C
I could understand what a struct means. But, i am bit confused with the difference between union and struct. Union is like a share of memory. What exactly it means.?
It may be more useful to have an uncontrived example of what this is good for. (I say "uncontrived" because most bit-banging uses of union are extremely treacherous. Bit-banging unions taken from big-endian to little-endian hardware break in the most (initially) mystifying ways.) (Of course, I've written bit-banging unions to tear apart floating point numbers to implement orders-of-magnitude-faster-than-the-library math functions. I just add assertions about which members are supposed to have the same addresses.)
This kind of construction is very common in X programming and other situations where one wishes to make a function that can receive many different types of messages (with different argument and layout requirements).
I've used unions to convert bytes to and from other types. I find it easier than bit-shifting.
Where int is 16-bit (was used on a micro controller).
Each member of a union shares the same memory. That means if you change one, you change the others. And if the members are of different types, this can have unpredictable results. (not exactly unpredictable, but hard to predict unless you are aware of the underlying bit patterns that make up the data members).
Most answers here are correct. A union is essentially a way to access same data in different ways (For example, you can access/interpret 4 bytes of memory as 1 integers, or as 4 characters). Structs as you know are straightforward - a collection of different, seprate objects with their own memory.
Usually you require Unions at a much later stage in programming as compared to Structs.
I suppose one way you can think of a union is that it is a set of aliases of varying type to a block of memory where each member of the union is an "alias" with a given type. Each alias refers to the same address in memory. How the bits at that address are interpreted are determined by the alias' type.
The amount of memory the union occupies is always equal to or possibly larger than the largest sized "member" of the union (due to alignment restrictions).
Run this program and find out the output.
#include < stdio.h >
You will find that the size of struct is double than that of union. This is because union has allocated space for only one variable while struct has allocated for two.