结构体数组如何包含另一个结构体数组中的元素
时间: 2023-12-20 18:32:46 浏览: 34
结构体数组可以包含另一个结构体数组中的元素。下面是一个示例代码,演示了如何实现这个功能:
```c
#include <stdio.h>
typedef struct student {
char name[20];
int age;
} Student;
typedef struct classroom {
Student students[5];
int numStudents;
} Classroom;
int main() {
Classroom classrooms[3];
// 初始化第一个班级的学生信息
strcpy(classrooms[0].students[0].name, "张三");
classrooms[0].students[0].age = 18;
strcpy(classrooms[0].students[1].name, "李四");
classrooms[0].students[1].age = 19;
classrooms[0].numStudents = 2;
// 初始化第二个班级的学生信息
strcpy(classrooms[1].students[0].name, "王五");
classrooms[1].students[0].age = 20;
strcpy(classrooms[1].students[1].name, "赵六");
classrooms[1].students[1].age = 21;
strcpy(classrooms[1].students[2].name, "钱七");
classrooms[1].students[2].age = 22;
classrooms[1].numStudents = 3;
// 初始化第三个班级的学生信息
strcpy(classrooms[2].students[0].name, "孙八");
classrooms[2].students[0].age = 23;
classrooms[2].numStudents = 1;
// 输出第二个班级的学生信息
for (int i = 0; i < classrooms[1].numStudents; i++) {
printf("姓名:%s,年龄:%d\n", classrooms[1].students[i].name, classrooms[1].students[i].age);
}
return 0;
}
```
这段代码定义了两个结构体:`Student`表示学生,`Classroom`表示班级。`Classroom`结构体中包含了一个`Student`结构体数组和一个表示学生数量的整数。通过这种方式,我们可以在一个结构体数组中存储多个班级的学生。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)