Professional Documents
Culture Documents
A structure is a collection of items of different types; and each data item will have its own memory location. Where
as only one item within the union can be used at any time, because the memory allocated for each item inside the
union is in a shared memory location i.e., only one memory location will be shared by the data items of union.
Sometimes we may not need the data of all the (related) data items of a complex data structure and be
storing/accessing only one data item at a time. Union helps in such scenarios.
e.g.,
typedef union
{
int Wind_Chill;
char Heat_Index;
} Condition;
typedef struct
{
float temp;
Condition feels_like;
} Temperature;
Wind Chill is only calculated when it is cold and heat index is used only when it is hot. There is no need for both of
them at the same time. So when we specify the temp, feels_like will have only one value - either wind chill or heat
index, but not both.
% cat structunion.c
#include <stdio.h>
#include <stdlib.h>
typedef union
{
int Wind_Chill;
char Heat_Index;
} Condition;
typedef struct
{
float temp;
Condition feels_like;
} Temperature;
void main()
{
Temperature *tmp;
Comments:
Great Content in your Blog... helps a lot refreshing some basic concepts... Thanks a lot....
# posted by Anonymous : 10:01 AM, April 27, 2007
The explanation is easy to understand.
# posted by JLPT : 4:43 AM, December 25, 2008
Simple but good explanation, thanks
# posted by matrix : 6:04 AM, April 06, 2009
simple,easy,good .
thanks
# posted by tushar : 9:29 PM, December 02, 2009
Simple and beneficial. Thanks.
# posted by Khairina : 12:16 AM, June 01, 2010
Post a Comment
Create a Link
<< Home
2004-2010