27-11-2012, 06:03 PM
STRUCTURES AND UNIONS
STRUCTURES AND UNIONS.pdf (Size: 69.3 KB / Downloads: 218)
INTRODUCTION
We studied earlier that array is a data structure whose element are
all of the same data type. Now we are going towards structure,
which is a data structure whose individual elements can differ in
type. Thus a single structure might contain integer elements,
floating– point elements and character elements. Pointers, arrays
and other structures can also be included as elements within a
structure. The individual structure elements are referred to as
members. This lesson is concerned with the use of structure within
a 'c' program. We will see how structures are defined, and how their
individual members are accessed and processed within a program.
The relationship between structures and pointers, arrays and
functions will also be examined. Closely associated with the structure
is the union, which also contains multiple members.
OBJECTIVES
After going through this lesson you will be able to
l explain the basic concepts of structure
l process a structure
l use typedef statement
l explain the between structures and pointers
PROCESSING A STRUCTURE
The members of a structure are usually processed individually, as
separate entities. Therefore, we must be able to access the individual
structure members. A structure member can be accessed by
writing
variable.member name.
This period (.) is an operator, it is a member of the highest precedence
group, and its associativity is left-to-right.
USER-DEFINED DATA TYPES (Typedef)
The typedef feature allows users to define new data types that are
equivalent to existing data types. Once a user-defined data type has
been established, then new variables, arrays, structure and so on,
can be declared in terms of this new data type.
PASSING STRUCTURES TO A FUNCTION
There are several different ways to pass structure–type information
to or from a function. Structure member can be transferred individually
, or entire structure can be transferred. The individual structures
members can be passed to a function as arguments in the
function call; and a single structure member can be returned via
the return statement. To do so, each structure member is treated
the same way as an ordinary, single- valued variable.
UNIONS
Union, like structures, contain members whose individual data types
may differ from one another. However, the members that compose a
union all share the same storage area within the computer’s memory
whereas each member within a structure is assigned its own unique
storage area. Thus, unions are used to conserve memory.