温馨提示×

c语言结构体数组怎么排序

小亿
125
2023-11-03 03:35:50
栏目: 编程语言

在C语言中,可以使用标准库函数qsort对结构体数组进行排序。下面是一个示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// 定义一个结构体
struct Person {
    char name[20];
    int age;
};

// 比较函数,用于指定排序规则
int compare(const void *a, const void *b)
{
    // 将void指针转换为结构体指针
    const struct Person *personA = (const struct Person *)a;
    const struct Person *personB = (const struct Person *)b;
    
    // 按照年龄升序排列
    if (personA->age < personB->age) {
        return -1;
    } else if (personA->age > personB->age) {
        return 1;
    } else {
        return 0;
    }
}

int main()
{
    struct Person people[] = {
        {"Alice", 25},
        {"Bob", 20},
        {"Charlie", 30}
    };
    
    int numPeople = sizeof(people) / sizeof(people[0]);
    
    // 使用qsort函数对结构体数组进行排序
    qsort(people, numPeople, sizeof(struct Person), compare);
    
    // 输出排序后的结果
    for (int i = 0; i < numPeople; i++) {
        printf("Name: %s, Age: %d\n", people[i].name, people[i].age);
    }
    
    return 0;
}

以上代码使用qsort函数对people数组进行排序,根据年龄的大小进行升序排列。

0