Read Sams Teach Yourself C in 24 Hours Online
Authors: Tony. Zhang
32: “the full moon grows.”
33: }
34: };
35: int i;
36:
37: for (i=0; i<2; i++)
38: DataDisplay(&poem[i]);
39:
40: return 0;
41: }
42: /* function definition */
43: void DataDisplay(HK *ptr_s)
44: {
45: printf(“%s\n”, ptr_s->str1);
46: printf(“%s\n”, ptr_s->str2);
continues
25 067231861x CH19 4.10.2000 11:04 AM Page 326
326
Hour 19
LISTING 19.5
continued
47: printf(“%s\n”, ptr_s->str3);
48: printf(“--- %s\n”, ptr_s->author);
49: printf(“ (%d-%d)\n\n”, ptr_s->start_year, ptr_s->end_year); 50: }
After running the executable (19L05.exe) of the program in Listing 19.5, I see the two pieces of Japanese haiku displayed on the screen of my computer:
Leading me along
OUTPUT
my shadow goes back home
from looking at the moon.
--- Sodo
(1641-1716)
A storm wind blows
out from among the grasses
the full moon grows.
--- Chora
(1729-1781)
In Listing 19.5, a structure data type, with the tag name of haiku, is declared in
ANALYSIS
lines 4–11. The structure data type contains two int variables and four char arrays as its members. The statement in line 13 creates a synonym, HK, for the struct haiku data type.
Then, in lines 19–34, an array of two elements, poem, is declared and initialized with two pieces of haiku written by Sodo and Chora, respectively. The following is a copy of the two pieces of haiku from poem:
“Leading me along”,
“my shadow goes back home”,
“from looking at the moon.”
and
“A storm wind blows”,
“out from among the grasses”,
“the full moon grows.”
The initializer also includes the author’s names and the years of their birth and death (refer to lines 20–22, and lines 27–29). Note that the poem array, declared with HK, is indeed an array of the haiku structure.
The DataDisplay() function is called twice in a for loop in lines 37 and 38. Each time, the address of an element of poem is passed to the DataDisplay() function. According to the definition of the function in lines 43–50, DataDisplay() prints out three strings of a haiku, the author’s name, and the period of time in which he lived.
25 067231861x CH19 4.10.2000 11:04 AM Page 327
Understanding Structures
327
From the output, you can see that the contents stored in the poem array of the haiku structure are displayed on the screen properly.
Nested Structures
You can declare a structure member that is itself a structure. For instance, given a structure data type of x, the following statement:
struct y {
int i;
char ch[8];
struct x nested;
};
declares a nested structure with tag name of y. One of the members of the y structure is a structure with the variable name of nested that is defined by the structure data type of x.
Listing 19.6 contains an example of using a nested structure to receive and print out information about an employee.
TYPE
LISTING 19.6
Using Nested Structures
1: /* 19L06.c Using nested structures */
2: #include
3:
4: struct department {
5: int code;
6: char name[32];
7: char position[16];
8: };
19
9:
10: typedef struct department DPT;
11:
12: struct employee {
13: DPT d;
14: int id;
15: char name[32];
16: };
17:
18: typedef struct employee EMPLY;
19:
20: void InfoDisplay(EMPLY *ptr);
21: void InfoEnter(EMPLY *ptr);
22:
23: main(void)
24: {
25: EMPLY info = {
continues
25 067231861x CH19 4.10.2000 11:04 AM Page 328
328
Hour 19
LISTING 19.6
continued
26: { 1,
27: “Marketing”,
28: “Manager”
29: },
30: 1,
31: “B. Smith”
32: };
33:
34: printf(“Here is a sample:\n”);
35: InfoDisplay(&info);
36:
37: InfoEnter(&info);
38:
39: printf(“\nHere are what you entered:\n”);
40: InfoDisplay(&info);
41:
42: return 0;
43: }
44: /* function definition */
45: void InfoDisplay(EMPLY *ptr)
46: {
47: printf(“Name: %s\n”, ptr->name);
48: printf(“ID #: %04d\n”, ptr->id);
49: printf(“Dept. name: %s\n”, ptr->d.name);
50: printf(“Dept. code: %02d\n”, ptr->d.code);
51: printf(“Your position: %s\n”, ptr->d.position);
52: }
53: /* function definition */
54: void InfoEnter(EMPLY *ptr)
55: {
56: printf(“\nPlease enter your information:\n”);
57: printf(“Your name:\n”);
58: gets(ptr->name);
59: printf(“Your position:\n”);
60: gets(ptr->d.position);
61: printf(“Dept. name:\n”);
62: gets(ptr->d.name);
63: printf(“Dept. code:\n”);
64: scanf(“%d”, &(ptr->d.code));
65: printf(“Your employee ID #:\n”);
66: scanf(“%d”, &(ptr->id));
67: }
When the executable file, 19L06.exe, is running, the initial content of the nested structure is printed out first. Then, I enter my employment information, which is in bold in the following output and displayed back on the screen too:
25 067231861x CH19 4.10.2000 11:04 AM Page 329
Understanding Structures
329
Here is a sample:
OUTPUT
Name: B. Smith
ID #: 0001
Dept. name: Marketing
Dept. code: 01
Your position: Manager
Please enter your information:\n”);
Your name:
T. Zhang
Your position:\n”);
Engineer
Dept. name:
R&D
Dept. code:
3
Your employee ID #:
1234
Here are what you entered:
Name: T. Zhang
ID #: 1234
Dept. name: R&D
Dept. code: 03
Your position: Engineer
There are two structure data types in Listing 19.6. The first one, called depart-ANALYSIS ment, is declared in lines 4–8. The second one, employee, declared in lines 12–16, contains a member of the department structure data type. Therefore, the employee structure data type is a nested structure data type.
19
Two synonyms, DPT for the struct department data type, and EMPLY for the struct employee data type, are created in two typedef statements respectively in lines 10 and 18. In the program, there are two functions, InfoDisplay() and InfoEnter(), whose prototypes are declared with a pointer to an EMPLY as an argument (see lines 20 and 21).
The statements in 25–32 initialize a nested structure, which is called info and has a data type of EMPLY. Note that the nested braces ({ and }) in lines 26 and 29 enclose the initializers for the d structure of DPT that is nested inside the info structure.
Then, the statement in line 35 displays the initial contents held by the nested info structure by calling the InfoDisplay() function. Line 37 calls the InfoEnter() function to ask the user to enter his or her employment information and then save it into the info structure. The InfoDisplay() function is called again in line 40 to display the information that was entered by the user and is now stored in the nested structure.
The definitions for the two functions, InfoDisplay() and InfoEnter(), are listed in lines 45–52 and lines 54–67, respectively.
25 067231861x CH19 4.10.2000 11:04 AM Page 330
330
Hour 19
Summary
In this lesson you learned the following very important concepts about structures in C:
• You can group variables of different types with a data type called a structure.
• The data items in a structure are called members of the structure.
• The struct keyword is used to start a structure declaration or a structure variable definition.
• The dot operator (.) is used to separate a structure name and a member name in referencing the structure member.
• The arrow operator (->) is commonly used to reference a structure member using a pointer to the structure.
• A structure can be passed to a function, and a function can return a structure back to the caller.
• Passing a pointer that points to a structure when calling a function is more efficient than passing the entire structure as an argument. Also, if a pointer is used, the function can modify the structure’s contents directly.
• Arrays of structures are permitted in C.
• You can enclose a structure within another structure. This is called a nested structure.
In the next lesson you’ll learn to use unions to collect dissimilar data items in C.
Q&A
Q Why do you need structures?
A
You often need to collect and group data items that are relevant to each other, but of different data types. The struct data type provides a convenient way to aggregate differently typed data items.
Q How do you reference a structure member?
A
You can reference a structure member by prefixing the structure member’s name with the structure variable name and a dot operator (.). If you are accessing the structure via a pointer, you can use the pointer name, the arrow operator (->), and then the member name to reference the structure member.
25 067231861x CH19 4.10.2000 11:04 AM Page 331
Understanding Structures
331
Q Why is it more efficient to pass a pointer that refers to a structure to a function?
A
When an entire structure is passed to a function, a copy of the structure is made and saved in a temporary block of storage. After the copy is modified by the function, it has to be returned and written back to the storage that holds the original content of the structure. Passing a function with a pointer that points to a structure, on the other hand, simply passes the address of the structure to the function instead of passing a copy of the entire structure. The function can then access the original memory location of the structure and modify the content held by the structure without duplicating the structure in temporary storage. Therefore, it’s more efficient to pass a pointer of a structure than to pass the structure itself to a function.
Workshop
To help solidify your understanding of this hour’s lesson, you are encouraged to answer the quiz questions and finish the exercises provided in the workshop before you move to the next lesson. The answers and hints to the questions and exercises are given in Appendix B, “Answers to Quiz Questions and Exercises.”
Quiz
1. What’s wrong with the following structure declaration?
struct automobile {
int year;
char model[8];
int engine_power;
19
float weight;
}
2. How many structure variables are defined in the following statement?
struct x {int y; char z} u, v, w;
3. Given a structure declaration
struct automobile {
int year;
char model[8]};
and two car models, Taurus and Accord, which are made in 1997, initialize an array of two elements, car, of the automobile structures.
25 067231861x CH19 4.10.2000 11:04 AM Page 332
332
Hour 19
Exercises
1. Given the following declaration and definition of a structure:
struct automobile {
int year;
char model[10];
int engine_power;
double weight;
} sedan = {
1997,
“New Model”,
200,
2345.67};
write a program to display on the screen the initial values held by the structure.
2. Rewrite the program in Listing 19.2. This time, create a function that can display the content in the employee structure. Then, make calls to the function by passing the structure to it.
3. Rewrite the program in Listing 19.4. This time, use the arrow operator (->) with the pointers to structures.
4. Rewrite the program in Listing 19.5. This time, add an array of pointers that is declared with HK. Then pass each element in the array of pointers to the DataDisplay() function.
26 067231861x CH20 1/25/00 10:59 AM Page 333
HOUR 20
Understanding Unions
Coming together is a beginning;
keeping together is progress;
working together is success.
—T. Roosevelt
In the previous hour’s lesson you learned how to store data of different types into structures. In this hour you’ll learn another way to collect differently typed data items by using unions. You’ll learn about the following topics in this lesson: