arrays - 按特定参数对 c 中的结构体数组进行排序

标签 arrays c sorting struct qsort

我有每个用户的结构,我正在尝试按用户姓氏对它们进行排序
完整代码:

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

struct phNum
{
    char name[30];
    char lastName[30];
    int phone;
};

typedef struct phNum PhNum;

PhNum phList[5] = {};
void showData() {
    for(int i = 0;i < 5;i++) {
        if(strcmp(phList[i].name,"empty") == 0 && phList[i].phone == 0){
            printf("%d : %s | %s | null\n", i+1,phList[i].name,phList[i].lastName);
        }
        else {
            printf("%d : %s | %s | %d\n", i+1,phList[i].name,phList[i].lastName,phList[i].phone);
        }
    }
}

数组最大为 5 项,最小为 0
我想按姓氏升序对它们进行排序,如果有 4 项,则不显示第五项。 我想覆盖我的数组 phList 并重写排序后的数组 我的 showData 函数应该进行排序和打印 我尝试了这些答案,但我不明白:How to sort an array of structs in C?How do I sort an array of structs in C by name, age and id?

我还尝试制作冒泡排序算法,但我很难将排序后的数据放入我的 phList

感谢您的帮助

最佳答案

首先,此声明

PhNum phList[5] = {};

在 C 中无效。与 C++ 相反,在 C 中您不能指定空大括号。

您可以像这样定义数组

PhNum phList[5] = { 0 };

要对数组进行排序,您可以使用标准 C 函数 qsort在 header <stdlib.h> 中声明.

您需要自己跟踪数组中有多少实际初始化的元素。您不能更改数组大小。

例如,如果数组包含 n初始化元素,其中 n大于0且小于或等于5然后你可以写

int cmp( const void *a, const void *b )
{
    const PhNum *p1 = a;
    const PhNum *p2 = b;

    return strcmp( p1->lastName, p2->lastName );
}    

在 main 中你可以写

qsort( phList, n, sizeof( *phList ), cmp );

关于arrays - 按特定参数对 c 中的结构体数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75135227/

相关文章:

C++ BigInteger 到字节数组

C: 数组的方括号之间可以有字符吗?

java - 如何将短数组转换为字节数组

c - 如何使用 getopt() 将 args 与参数分组

python - 如何根据python中的列表对字典进行排序

python - 从 numpy.array 中删除多个项目而不使用 numpy.delete

c - 我如何使用 sscanf 接受零作为输入,但不接受非数字输入?

c - 我的程序无限循环,我真的不知道为什么

java - 有没有办法向 Eclipse 的 "Sort all members"添加排除项?

javascript - 覆盖排序索引