C语言中结构体是一种自定义的数据类型,它可以将不同类型的数据组合在一起形成一个新的数据类型。结构体数组就是由多个相同结构体类型的变量组成的数组。
1. 结构体数组的定义
结构体数组的定义格式为:
```
```
小诺霉素
其中,结构体名表示定义结构体时所使用的名称,数组名表示定义结构体数组时所使用的名称,元素个数表示该结构体数组中元素的数量。
例如,我们可以定义一个学生信息的结构体,并创建一个包含5个学生信息的结构体数组:
```
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
南京邮电大学张代远
float score;
};
int main() {
struct Student students[5];
return 0;
}
```
2. 结构体数组元素赋值
我们可以通过下标来访问和修改结构体数组中每个元素的值。例如,我们可以给第一个学生赋值:
```
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
float score;
};猴耳环
int main() {
struct Student students[5];
strcpy(students[0].name, "Tom");
students[0].age = 18;
students[0].score = 90.5;大胆的爱小心的偷
return 0;
}
```
3. 遍历输出结构体数组
我们可以使用循环语句来遍历输出整个结构体数组中的所有元素。例如,我们可以输出所有学生的信息:
```
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int age;
float score;
};
int main() {
struct Student students[5];
strcpy(students[0].name, "Tom");
students[0].age = 18;
students[0].score = 90.5;
strcpy(students[1].name, "Jerry");
students[1].age = 19;
students[1].score = 85.5;
一战 strcpy(students[2].name, "Mike");
students[2].age = 20;
students[2].score = 95.0;
strcpy(students[3].name, "Mary");
students[3].age = 21;
students[3].score = 88.0;
se18mm strcpy(students[4].name, "Lucy");
students[4].age = 22;
students[4].score = 92.5;
for (int i=0; i<5; i++) {
printf("Name:%s\n",students[i].name);
printf("Age:%d\n",students[i].age);
printf("Score:%.2f\n",students[i].score);
printf("\n");
}
return 0;
}
```
4. 结构体数组的排序
我们可以使用冒泡排序等算法对结构体数组进行排序。例如,我们可以按照学生成绩从高到低进行排序: