Programming in C

(Barry) #1
4.0 Data Types and Declarations 435

Va r iables can be declared at the time that the structure is defined simply by listing
them before the terminating semicolon, or they can subsequently be declared using the
format
struct name variableList;
This format cannot be used if nameis omitted when the structure is defined. In that
case, all variables of that structure type must be declared with the definition.
The format for initializing a structure variable is similar to that for arrays. Its members
can be initialized by enclosing the list of initial values in a pair of curly braces. Each
value in the list must be a constant expression if a global structure is initialized.
The declaration
struct point
{
float x;
float y;
} start = {100.0, 200.0};
defines a structure called pointand a struct pointvariable called startwith initial
values as specified. Specific members can be designated for initialization in any order
with the notation
.member = value
in the initialization list, as in
struct point end = { .y = 500, .x = 200 };
The declaration
struct entry
{
char *word;
char *def;
} dictionary[1000] = {
{ "a", "first letter of the alphabet" },
{ "aardvark", "a burrowing African mammal" },
{ "aback", "to startle" }
};
declares dictionaryto contain 1,000 entrystructures, with the first three elements ini-
tialized to the specified character string pointers. Using designated initializers, you could
have also written it like this:
struct entry
{
char *word;
char *def;
} dictionary[1000] = {
[0].word = "a", [0].def = "first letter of the alphabet",

20 0672326663 AppA 6/10/04 2:01 PM Page 435

Free download pdf