c语言结构体二维数组
时间: 2023-08-24 07:21:02 浏览: 52
结构体数组的初始化-第10章 复杂数据类型
C语言中可以使用结构体二维数组,实现对多个结构体的管理和操作。下面是一个示例代码:
```
#include <stdio.h>
struct student {
char name[20];
int age;
float score;
};
int main() {
struct student stu[3][4] = {
{{"Tom", 18, 80.5f}, {"Jerry", 19, 90.5f}, {"Lucy", 20, 70.5f}, {"Lily", 21, 85.5f}},
{{"Jack", 22, 75.5f}, {"Bob", 23, 88.5f}, {"Mike", 24, 92.5f}, {"John", 25, 71.5f}},
{{"Mary", 26, 93.5f}, {"Alice", 27, 84.5f}, {"David", 28, 79.5f}, {"Frank", 29, 86.5f}}
};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 4; j++) {
printf("Name: %s, Age: %d, Score: %.1f\n", stu[i][j].name, stu[i][j].age, stu[i][j].score);
}
printf("\n");
}
return 0;
}
```
在这个示例代码中,定义了一个名为`student`的结构体,包含学生的姓名、年龄和成绩。然后定义了一个二维数组`stu`,用于存储多个`student`结构体,数组的第一维表示学生的组别,第二维表示学生的编号。
在主函数中,使用`for`循环遍历二维数组`stu`,并输出每个学生的信息。运行程序后,输出的结果应该类似于以下内容:
```
Name: Tom, Age: 18, Score: 80.5
Name: Jerry, Age: 19, Score: 90.5
Name: Lucy, Age: 20, Score: 70.5
Name: Lily, Age: 21, Score: 85.5
Name: Jack, Age: 22, Score: 75.5
Name: Bob, Age: 23, Score: 88.5
Name: Mike, Age: 24, Score: 92.5
Name: John, Age: 25, Score: 71.5
Name: Mary, Age: 26, Score: 93.5
Name: Alice, Age: 27, Score: 84.5
Name: David, Age: 28, Score: 79.5
Name: Frank, Age: 29, Score: 86.5
```
阅读全文