c语言程序设计第五版第九章
时间: 2023-11-22 20:04:52 浏览: 116
第五版的C语言程序设计第九章主要讲解了用户自己建立数据类型,包括结构体和联合体的定义、初始化、访问和使用等内容。具体包括以下几个方面:
1. 结构体的定义和使用
结构体是一种用户自定义的数据类型,可以将不同类型的数据组合在一起,形成一个新的数据类型。结构体的定义格式为:
```c
struct 结构体名 {
数据类型1 成员名1;
数据类型2 成员名2;
...
};
```
结构体的成员可以通过“.”运算符进行访问,例如:
```c
struct Student {
char name[20];
int age;
float score;
};
struct Student stu1 = {"Tom", 18, 90.5};
printf("Name: %s, Age: %d, Score: %.1f\n", stu1.name, stu1.age, stu1.score);
```
2. 结构体指针的使用
结构体指针可以指向结构体变量,也可以指向动态分配的结构体内存。结构体指针的定义格式为:
```c
struct 结构体名 *指针变量名;
```
结构体指针的成员访问可以使用“->”运算符,例如:
```c
struct Student stu2 = {"Jerry",20, 85.0};
struct Student *p = &stu2;
printf("Name: %s, Age: %d, Score: %.1f\n", p->name, p->age, p->score);
```
3. 联合体的定义和使用
联合体是一种特殊的结构体,所有成员共用同一块内存空间,不同成员的值会互相影响。联合体的定义格式为:
```c
union 联合体名 {
数据类型1 成员名1;
数据类型2 成员名2;
...
};
```
联合体的成员访问可以使用“.”运算符,例如:
```c
union Data {
int i;
float f;
char str[20];
};
union Data data;
data.i = 10;
printf("data.i: %d\n", data.i);
data.f = 3.14;
printf("data.f: %.2f\n", data.f);
strcpy(data.str, "hello");
printf("data.str: %s\n", data.str);
```
4. 枚举类型的定义和使用
枚举类型是一种用户自定义的数据类型,可以将一组相关的常量定义为一个枚举类型。枚举类型的定义格式为:
```c
enum 枚举类型名 {
枚举常量1,
枚举常量2,
...
};
```
枚举类型的变量可以直接赋值为枚举常量,例如:
```c
enum Color {RED, GREEN, BLUE};
enum Color c = GREEN;
printf("c: %d\n", c);
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![text/x-c](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)