Moät soá kieán thöùc cô sôû veà laäp trình baèng ngoân ngöõ C

Phaâàn tröôùc | Muïc luïc | Phaâàn sau

XIX. Caáu truùc (struct)

Noäi dung:

 

Khai baùo vaø ñònh nghóa caáu truùc

Caáu truùc laø moät daïng döõ lieäu taäp hôïp soá lieäu vôùi caùc kieåu khaùc nhau.

struct struct_tag {
     data_type1 variable1;
     data_type2 variable2;
     data_type3 variable3;
     .
     .
     .
     };

struct laø töø khoùa C khai baùo caáu truùc, struct_tag laø teân tag caáu truùc, caùc thaønh phaàn trong {} laø caùc kieåu döõ lieäu ñöôïc taäp hôïp.

Ví duï:

 
struct automobile {
     int year;
     char model[8];
     int engine_power;
     float weight;
     };

Ñònh nghóa bieán caáu truùc

struct automobile sedan, pick_up, sport_utility;

hoaëc moät caùch toång hôïp

struct automobile {
     int year;
     char model[8];
     int engine_power;
     float weight;
     } sedan, pick_up, sport_utility;

Tham chieáu phaàn töû caáu truùc

Ta duøng daáu chaám (.) ñeå tham chieáu phaàn töû caáu truùc nhö sau:

sedan.year = 1997;
ptr = sedan.model;

Ví duï:

 
1:  /* Access to structure members */
2:  #include <stdio.h>
3:
4:  main(void)
5:  {
6:     struct computer {
7:        float cost;
8:        int year;
9:        int cpu_speed;
10:       char cpu_type[16];
11:       } model;
12:
13:    printf("The type of the CPU inside your computer?\n");
14:       gets(model.cpu_type);
15:    printf("The speed(MHz) of the CPU?\n");
16:       scanf("%d", &model.cpu_speed);
17:    printf("The year your computer was made?\n");
18:       scanf("%d", &model.year);
19:    printf("How much you paid for the computer?\n");
20:       scanf("%f", &model.cost);
21:
22:    printf("Here are what you entered:\n");
23:    printf("Year: %d\n", model.year);
24:    printf("Cost: $%6.2f\n", model.cost);
25:    printf("CPU type: %s\n", model.cpu_type);
26:    printf("CPU speed: %d MHz\n", model.cpu_speed);
27:
28:    return 0;
29: }
 
Keát quaû:
 
The type of the CPU inside your computer?
Pentium
The speed(MHz) of the CPU?
100
The year your computer was made?
1996
How much you paid for the computer?
1234.56
Here are what you entered:
Year: 1996
 
Cost: $1234.56

CPU type: Pentium
CPU speed: 100 MHz

Gaùn giaù trò cho caáu truùc

Ví duï:

1:  /* Initializing a structure */
2:  #include <stdio.h>
3:
4:  main(void)
5:  {
6:     struct employee {
7:        int id;

8:        char name[32];
9:        };
10:    /* structure initialization */
11:    struct employee info = {
12:       1,
13:       "B. Smith"
14:       };
15:
16:    printf("Here is a sample:\n");
17:    printf("Employee Name: %s\n", info.name);
18:    printf("Employee ID #: %04d\n\n", info.id);
19:
20:    printf("What's your name?\n");
21:       gets(info.name);
22:    printf("What's your ID number?\n");
23:       scanf("%d", &info.id);
24:
25:    printf("\nHere are what you entered:\n");
26:    printf("Name: %s\n", info.name);
27:    printf("ID #: %04d\n", info.id);
28:
29:    return 0;
30: }
 
Keát quaû:
 
Here is a sample:
Employee Name: B. Smith
Employee ID #: 0001
 
What's your name?
T. Zhang
What's your ID number?
1234
 
Here are what you entered:
Name: T. Zhang
ID #: 1234

Caáu truùc vaø haøm

Trong C, ta coù theå chuyeån döõ lieäu daïng caáu truùc cho haøm vaø xuaát giaù trò haøm döôùi daïng caáu truùc.

Ví duï:

1:  /* Passing a structure to a function */
2:  #include <stdio.h>
3:
4:  struct computer {
5:     float cost;
6:     int year;
7:     int cpu_speed;
8:     char cpu_type[16];
9:  };
10: /* create synonym */
11: typedef struct computer SC;
12: /* function declaration */
13: SC DataReceive(SC s);
14:
15: main(void)
16: {
17:    SC model;
18:
19:    model = DataReceive(model);
20:    printf("Here are what you entered:\n");
21:    printf("Year: %d\n", model.year);
22:    printf("Cost: $%6.2f\n", model.cost);
23:    printf("CPU type: %s\n", model.cpu_type);
24:    printf("CPU speed: %d MHz\n", model.cpu_speed);
25:
26:    return 0;
27: }
28: /* function definition */
29: SC DataReceive(SC s)
30: {
31:    printf("The type of the CPU inside your computer?\n");
32:       gets(s.cpu_type);
33:    printf("The speed(MHz) of the CPU?\n");
34:       scanf("%d", &s.cpu_speed);
35:    printf("The year your computer was made?\n");
36:       scanf("%d", &s.year);
37:    printf("How much you paid for the computer?\n");
38:       scanf("%f", &s.cost);
39:    return s;
40: }
 
Keát quaû:
 
The type of the CPU inside your computer?
Pentium
The speed(MHz) of the CPU?
100
The year your computer was made?
1996
How much you paid for the computer?
1234.56
Here are what you entered:
Year: 1996
Cost: $1234.56
CPU type: Pentium
CPU speed: 100 MHz

Con troû chæ ñeán caáu truùc

Ví duï:

1:  /* Pointing to a structure */
2:  #include <stdio.h>
3:
4: struct computer {

5:    float cost;
6:    int year;
7:    int cpu_speed;
8:    char cpu_type[16];
9: };
10:
11: typedef struct computer SC;
12:
13: void DataReceive(SC *ptr_s);
14:
15: main(void)
16: {
17:    SC model;
18:
19:    DataReceive(&model);
20:    printf("Here are what you entered:\n");
21:    printf("Year: %d\n", model.year);
22:    printf("Cost: $%6.2f\n", model.cost);
23:    printf("CPU type: %s\n", model.cpu_type);
24:    printf("CPU speed: %d MHz\n", model.cpu_speed);
25:
26:    return 0;
27: }
28: /* function definition */
29: void DataReceive(SC *ptr_s)
30: {
31:    printf("The type of the CPU inside your computer?\n");
32:       gets((*ptr_s).cpu_type);
33:    printf("The speed(MHz) of the CPU?\n");
34:       scanf("%d", &(*ptr_s).cpu_speed);
35:    printf("The year your computer was made?\n");
36:       scanf("%d", &(*ptr_s).year);
37:    printf("How much you paid for the computer?\n");
38:       scanf("%f", &(*ptr_s).cost);
39: }
 
Keát quaû:
 
The type of the CPU inside your computer?
Pentium
The speed(MHz) of the CPU?
100
The year your computer was made?
1996
How much you paid for the computer?
1234.56
Here are what you entered:
Year: 1996
Cost: $1234.56
CPU type: Pentium
CPU speed: 100 MHz

Tham chieáu phaàn töû caáu truùc baèng toaùn töû ->

Ta coù theå duøng -> ñeå truy caäp moät phaàn töû cuûa caáu truùc khi ñaõ coù con troû chæ ñeán caáu truùc ñoù.

Ví duï:  Thay vì vieát (*ptr_s).cpu_type ta coù theå vieát

ptr_s -> cpu_type

hoaëc thay cho &(*ptr_s).cpu_speed ta vieát:

 
&(ptr_s->cpu_speed)

Laäp trình vieân C thöôøng duøng -> thay cho (.) vì noù roõ raøng hôn.

Maûng caáu truùc

struct x array_of_structure[8];

khai baùo moät maûng array_of_structure vôùi kieåu caáu truùc x vaø coù 8 phaàn töû.

Ví duï:

1:  /* Arrays of structures */
2:  #include <stdio.h>
3:
4:  struct haiku {
5:     int start_year;
6:     int end_year;
7:     char author[16];
8:     char str1[32];
9:     char str2[32];
10:    char str3[32];
11: };
12:
13: typedef struct haiku HK;
14:
15: void DataDisplay(HK *ptr_s);
16:
17: main(void)
18: {
19:    HK poem[2] = {
20:      { 1641,
21:        1716,
22:        "Sodo",
23:        "Leading me along",
24:        "my shadow goes back home",
25:        "from looking at the moon."
26:      },
27:      { 1729,
28:        1781,
29:        "Chora",
30:        "A storm wind blows",
31:        "out from among the grasses",
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);
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: }
 
Keát quaû:
 
Leading me along
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)

Caáu truùc loàng

Ví duï:

struct y {
   int i;
   char ch[8];
   struct x nested;
};

Ví duï:

1:  /* Using nested structures */
2:  #include <stdio.h>
3:
4:  struct department {
5:     int  code;
6:     char name[32];
7:     char position[16];
8:  };
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 = {
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: }
 
Keát quaû:
 
Here is a sample:
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

Caáu truùc tham chieáu tröôùc (forward-referencing structure)

Neáu moät trong caùc phaàn töû cuûa caáu truùc laø döõ lieäu kieåu caáu truùc nhöng chöa ñöôïc khai baùo, caáu truùc ñoù ñöôïc goïi laø caáu truùc tham chieáu tröôùc.

Caáu truùc töï chieáu tröôùc (self-referencing structure)

struct x {
   int i;
   char ch[8];
   struct x *ptr;
};

Ví duï:

1:  /* Forward-referencing structures */
2:  #include <stdio.h>
3:  /* forward-referencing structure */
4:  struct resume {
5:     char name[16];
6:     struct date *u;
7:     struct date *g;
8:  };
9:  /* referenced structure */
10: struct date {
11:    int year;
12:    char school[32];
13:    char degree[8];
14: };
15:
16: typedef struct resume RSM;
17: typedef struct date DATE;
18:
19: void InfoDisplay(RSM *ptr);
20:
21: main(void)
22: {
23:    DATE under = {
24:        1985,
25:        "Rice University",
26:        "B.S."
27:        };
28:    DATE graduate = {
29:        1987,
30:        "UT Austin",
31:        "M.S."
32:        };
33:    RSM new_employee = {
34:        "Tony",
35:        &under,
36:        &graduate
37:        };
38:
39:    printf("Here is the new employee's resume:\n");
40:    InfoDisplay(&new_employee);
41:
42:    return 0;
43: }
44: /* function definition */
45: void InfoDisplay(RSM *ptr)
46: {
47:    printf("Name: %s\n", ptr->name);
48:    /* undergraduate */
49:    printf("School name: %s\n", ptr->u->school);
50:    printf("Graduation year: %d\n", ptr->u->year);
51:    printf("Degree: %s\n", ptr->u->degree);
52:    /* graduate */
53:    printf("School name: %s\n", ptr->g->school);
54:    printf("Graduation year: %d\n", ptr->g->year);
55:    printf("Degree: %s\n", ptr->g->degree);
56: }
 
Keát quaû:
 
Here is the new employee's resume:
Name: Tony
School name: Rice University
Graduation year: 1985
Degree: B.S.
School name: UT Austin
Graduation year: 1987
Degree: M.S.
C:\app>
 

Caûnh baùo

C cho pheùp tham chieáu tröôùc trong struct, nhöng neáu coù leänh typedef thi tham chieáu tröôùc khoâng cho pheùp (error!).

Baøi taäp

  1. Coù gì sai trong khai baùo sau:
struct automobile {
     int year;
     char model[8];
     int engine_power;
     float weight;
     }
  1. Cho caáu truùc sau
struct automobile {
     int year;
     char model[8]};

vaø 2 xe Taurus vaø Accord, cheá taïo naêm 1977. Haõy gaùn caùc giaù trò vöøa cho cho caáu truùc treân.

  1. Trong caùc caáu truùc sau, caùi naøo laø töï tham chieáu hoaëc tham chieáu tröôùc?
struct member {
     char name[32];
     struct employment *emp;
     struct education *edu;};
 
struct list {
     int x, y;
     float z;
     struct list *ptr_list;};
 

Phaâàn tröôùc | Muïc luïc | Phaâàn sau