| I l @ ve RuBoard |
12.6 Arrays of StructuresStructures 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
/* * 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
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
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
};
You can now declare an array to hold the mailing list: /* Our mailing list */ struct mailing list[MAX_ENTRIES]; |
| I l @ ve RuBoard |
| I l @ ve RuBoard |
12.7 Programming ExercisesExercise 12-1: Design a data structure to handle the data for a mailing list. Exercise 12-2: Design a structure to store time and date. Write a function to find the difference between two times in minutes. Exercise 12-3: Design an airline reservation data structure that contains the following data:
Write a program that lists all planes leaving from two airports specified by the
|
| I l @ ve RuBoard |
| I l @ ve RuBoard |
12.8 Answers to Chapter QuestionsAnswer 12-1: The problem is that we have a single signed-integer-bit field. A three-bit-wide signed-integer field can take on the following values:
struct foo {
int three_bits:3;
};
A two-bit-wide signed-integer field can take on the following values:
struct foo {
int two_bits:3;
};
A one-bit-wide signed-integer field can take on the following values:
struct foo {
int one_bit:1;
};
So the two values of this bit field are 0 and -1. That means that 1 can never be stored in this field. A unsigned bit field of width 1 can hold the values 0 and 1. Using the declaration unsigned int valid:1 makes the program work correctly. |
| I l @ ve RuBoard |