C语言以结构体数组中某个成员大小进行排序。
时间: 2023-10-18 20:40:18 浏览: 309
要按照结构体数组中某个成员的大小进行排序,可以使用C语言的标准库函数`qsort`来实现。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义一个结构体
struct Person {
char name[50];
int age;
};
// 比较函数,用于指定排序规则
int compare(const void *a, const void *b) {
// 将void指针转换为结构体指针
const struct Person *p1 = (const struct Person *)a;
const struct Person *p2 = (const struct Person *)b;
// 按照年龄进行升序排序
return p1->age - p2->age;
}
int main() {
struct Person people[3];
// 输入结构体数组的值
for (int i = 0; i < 3; i++) {
printf("输入姓名:");
scanf("%s", people[i].name);
printf("输入年龄:");
scanf("%d", &people[i].age);
}
// 使用qsort函数进行排序
qsort(people, 3, sizeof(struct Person), compare);
// 输出排序后的结果
printf("排序后的结果:\n");
for (int i = 0; i < 3; i++) {
printf("姓名:%s,年龄:%d\n", people[i].name, people[i].age);
}
return 0;
}
```
在这个示例中,我们首先定义了一个名为`Person`的结构体,其中包含两个成员变量`name`和`age`。然后在主函数中声明了一个名为`people`的结构体数组,用于存储多个人的信息。
接下来,我们使用循环遍历结构体数组,使用`scanf`函数分别输入每个人的姓名和年龄。
然后,我们定义了一个比较函数`compare`,用于指定排序规则。在这个示例中,我们按照年龄进行升序排序。
最后,我们使用`qsort`函数对结构体数组进行排序。参数`people`是要排序的数组的首地址,参数`3`表示数组的长度,参数`sizeof(struct Person)`表示每个元素的大小,参数`compare`是比较函数的名称。
最后,我们输出排序后的结果。
请注意,在实际应用中,可能需要进行输入验证和错误处理,以确保输入的数据类型和范围符合预期。这个示例只是一个简单的演示。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)