Sams Teach Yourself C in 21 Days

(singke) #1
Implementing Structures, Unions, and TypeDefs 255

11


You could have combined the definition and declaration, as you did before for the type
coord:
struct rectangle {
struct coord topleft;
struct coord bottomrt;
} mybox;
To access the actual data locations (the type intmembers), you must apply the member
operator (.) twice. Thus, the expression
mybox.topleft.x
refers to the xmember of the topleftmember of the type rectanglestructure named
mybox. To define a rectangle with coordinates ( 0 , 10 ),( 100 , 200 ), you would write
mybox.topleft.x = 0;
mybox.topleft.y = 10;
mybox.bottomrt.x = 100;
mybox.bottomrt.y = 200;
Maybe this is a bit confusing. You will understand better if you look at Figure 11.1,
which shows the relationship between the type rectanglestructure, the two type coord
structures it contains, and the two type intvariables each type coordstructure contains.
These structures are named as in the preceding example.

FIGURE11.1
The relationship
between a structure,
structures within a
structure, and the
structure members.

mybox.topleft.x
mybox.topleft.y

mybox.bottomrt.x
mybox.bottomrt.y

{

{

{

{

A type int variable (x)
A type int variable (y)

A type int variable (x)
A type int variable (y)

{


{


A type coord
structure (topleft)

A type coord
structure (bottomrt)

A type rectangle
structure (mybox)
{

Listing 11.2 presents an example of using structures that contain other structures. This
listing takes input from the user for the coordinates of a rectangle and then calculates and
displays the rectangle’s area. Note the program’s assumptions, given in comments near
the start of the program (lines 3 through 8).

LISTING11.2 struct.c. A demonstration of structures that contain other structures
1: /* Demonstrates structures that contain other structures. */
2:
3: /* Receives input for corner coordinates of a rectangle and
4: calculates the area. Assumes that the y coordinate of the
5: lower-right corner is greater than the y coordinate of the

18 448201x-CH11 8/13/02 11:17 AM Page 255

Free download pdf