I l@ve RuBoard Previous Section Next Section

12.6 Arrays of Structures

Structures and arrays can be combined. Suppose you want to record the time a runner completes each lap of a four-lap race. You define a structure to store the time:

struct time { 
    int hour;   // Hour (24-hour clock)
    int minute; // 0-59
    int second; // 0-59
}; 

const int MAX_LAPS = 4; /* We will have only 4 laps*/ 

/* The time of day for each lap*/ 
struct time lap[MAX_LAPS]; 

The statement:

struct time lap[MAX_LAPS]; 

defines lap as an array of four elements. Each element consists of a single time structure.

You can use this as follows:

/* 
 * Runner just past the timing point 
 */ 

assert((count >= 0) && (count <= sizeof(lap)/sizeof(lap[0])));
lap[count].hour = hour; 
lap[count].minute = minute; 
lap[count].second = second; 
++count; 

This array can also be initialized when the variable is declared. Initialization of an array of structures is similar to the initialization of multidimensional arrays:

struct time start_stop[2] = { 
    {10, 0, 0}, 
    {12, 0, 0} 
}; 

Suppose you want to write a program to handle a mailing list. Mailing labels are 5 lines high and 60 characters wide. You need a structure to store names and addresses. The mailing list will be sorted by name for most printouts, and in Zip-code order for actual mailings. The mailing list structure looks like this:

struct mailing { 
    char name[60];    // Last name, first name
    char address1[60];// Two lines of street address
    char address2[60]; 
    char city[40];    // Name of the city 
    char state[2];    // Two-character abbreviation[2]
    long int zip;     // Numeric zip code
}; 

[2] To store the state abbreviation as a C-style string, three characters are needed; two for the data and one for the end-of-string character. This is not a C-style string. Instead it is just two characters. So the dimension 2 is correct.

You can now declare an array to hold the mailing list:

/* Our mailing list */ 
struct mailing list[MAX_ENTRIES]; 
    I l@ve RuBoard Previous Section Next Section