STRUCTURES AND UNIONS
STRUCTURE:
A collection of one or more
variables, may be different types,
grouped together under a single
name.
Basic Object of Graphics is a point which
can be assumed to have an x coordinate
and a y coordinate.
Considering both of them as integers, the
two components can be declared in a
structure asstruct point
{
int x;
int y;
};
struct:
• structure declaration
• list of declarations enclosed
in braces.
• defining a type
// point is structure tag
struct point
{
int x;
int y;
};
Members:
Variables named in a
structure
Structure Tag, structure
member , non-member variable
can have the same name
without conflict.
They can be distinguished from
each other by context.
Same member name(s) may
occur in different structures.
The right brace that terminates the
list of members may be followed by a
list of variables.
struct { … } x,y,z;
Structure declaration not being followed
by a list of variables reserves no storage.
Tag in declaration can later be used in
definitions of instances of the structure.
struct point pt;
-Here variable pt which is a
structure of type struct point
struct point maxpt={320,200};
-The structure is initialized
following its definition.
A member of a structure is
referred to using an expression
of the following formatstructure-name.member
“.” is an operator.
ARRAY OF STRUCTURES
An array of structures is
a collection of numerous
structure variables containing
data about different
entities.
The array of structures can also be described as
a collection of structure variables.
UNION
union u_tag
{
int ival;
float fval;
char *sval;
}u;
Members can be accessed as
union_name.member;
Size:
Structures do not have shared location for
their members, so the size of a Structure is
equal to the sum of size of all the data
members.
Unions do not have separate locations for
each of their members, so their size or
equal to the size of largest member
among all data members.
Value storage:
In a Structure, there is specific memory
location for each input data member and
hence it can store multiple values of
the different members.
In a Union, there is only one shared
memory allocation for all input data
members so it stores a single value at
a time for all members.