Structures and unions provide a way to group common variables
together. To define a structure use:
struct structure-name {
variables,...
} structure-variables,...;
Structure-name is optional and not needed if the
structure variables are defined. Inside it can contain any
number of variables separated by semicolons. At the end,
structure-variables defines the actual names of the
individual structures. Multiple structures can be defined by
separating the variable names with commas. If no
structure-variables are given, no variables are created.
Structure-variables can be defined separately by specifying:
struct structure-name
new-structure-variable;
new-structure-variable will be created and has a separate
instance of all the variables in structure-name.
To access a variable in the structure, you must use a record
selector (. ).
Unions work in the same way as structures except that all
variables are contained in the same location in memory. Enough
space is allocated for only the largest variable in the union.
All other variables must share the same memory location. Unions
are defined using the union keyword.
Examples:
struct my-structure {
int fred[5];
char wilma, betty;
float barny=1;
};
This defines the structure my-structure, but nothing has yet
been done.
struct my-structure account1;
This creates account1 and it has all of the variables from
my-structure. account1.barny contains the value "1".
union my-union {
char character_num;
int integer_num;
long long_num;
float float_num;
double double_num;
} number;
This defines the union number and allocates just enough
space for the variable double_num.
number.integer_num=1;
Sets the value of integer_num to "1".
number.float_num=5;
Sets the value of float_num to "5".
printf("%i",integer_num);
This is undefined since the location of integer_num was
overwritten in the previous line by float_num.
|