Can we use pointer in union?

Chandrakant picture Chandrakant · Jan 20, 2011 · Viewed 21.5k times · Source

If no why? Uses of union over structure??

Answer

paxdiablo picture paxdiablo · Jan 20, 2011

You can use any data type in a union, there's no restriction.

As to the use of unions over structures, structures lay out their data sequentially in memory. This mean all their sub-components are separate.

Unions, on the other hand, use the same memory for all their sub-components so only one can exist at a time.

For example:

                                 +-----+-----+
struct { int a; float b }  gives |  a  |  b  |
                                 +-----+-----+
                                    ^     ^
                                    |     |
                 memory location:  150   154
                                    |
                                    V
                                 +-----+
union { int a; float b }  gives  |  a  |
                                 |  b  |
                                 +-----+

Structures are used where an "object" is composed of other objects, like a point object consisting of two integers, those being the x and y coordinates:

typedef struct {
    int x;           // x and y are separate
    int y;
} tPoint;

Unions are typically used in situation where an object can be one of many things but only one at a time, such as a type-less storage system:

typedef enum { STR, INT } tType;
typedef struct {
    tType typ;          // typ is separate.
    union {
        int ival;       // ival and sval occupy same memory.
        char *sval;
    }
} tVal;

They are useful for saving memory although that tends to be less and less of a concern nowadays (other than in low-level work like embedded systems) so you don't see a lot of it.