Sams Teach Yourself C in 21 Days

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

11


These statements define the structure type coordand declare two structures,firstand
second, of type coord.firstandsecondare each instancesof type coord;firstcon-
tains two integer members named xandy, and so does second.
This method of declaring structures combines the declaration with the definition. The
second method is to declare structure variables at a different location in your source code
from the definition. The following statements also declare two instances of type coord:
struct coord {
int x;
int y;
};
/* Additional code may go here */
struct coord first, second;
In this example, you can see that the definition of the coordstructure is separate from
the declaration of variables. When declaring variables separately, you use the struct
keyword followed by the structured tag followed by the name of the variable or variables
you want to create.

Accessing Members of a Structure ..............................................................

Individual structure members can be used like other variables of the same type. Structure
members are accessed using the structure member operator(.), also called the dot oper-
ator,between the structure name and the member name. Thus, to have the structure
namedfirstrefer to a screen location that has coordinates x=50,y=100, you could write
first.x = 50;
first.y = 100;
To display the screen locations stored in the structure second, you could write
printf(ā€œ%d,%dā€, second.x, second.y);
At this point, you might be wondering what the advantage is of using structures rather
than individual variables. One major advantage is that you can copy information between
structures of the same type with a simple equation statement. Continuing with the pre-
ceding example, the statement
first = second;
is equivalent to this statement:
first.x = second.x;
first.y = second.y;
When your program uses complex structures with many members, this notation can be a
great time-saver. Other advantages of structures will become apparent as you learn some

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

Free download pdf