我有每个用户的结构,我正在尝试按用户姓氏对它们进行排序
完整代码:
#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/