我有这部分,首先(我将用它来创建员工结构):
typedef struct
{
char first_name[20], last_name[20];
int birthdate, temporary;
//date of birth YEAR/MONTH/DAY
//temporary employees: 1, else 0
}factory;
我将使用以下函数读取数据:
void reading(factory *employee,int *nr)
{
++(*nr);
printf("First name:\n");
fflush(stdin);
gets((employee+*nr)->first_name);
printf("Last name:\n");
fflush(stdin);
gets((employee+*nr)->last_name);
printf("Birthdate:\n");
fflush(stdin);
scanf ("%d" , &((employee + *nr)->birthdate));
printf("Temporary employee? 1 for YES, 0 for NO");
fflush(stdin);
scanf("%d", &((employee + *nr)->temporary));
}
还有比较函数(我认为它写得不正确,任何关于如何修改它的建议都很好——它应该是“工厂员工 *ia”而不是结构吗?):
int struct_cmp_by_name(const void *a, const void *b)
{
struct employee *ia = (struct employee *)a;
struct employee *ib = (struct employee *)b;
return strcmp(ia->last_name, ib->last_name);
}
我还有一个简单的显示函数,我将在下面复制其原型(prototype):
void display(factory *employee, int nr)
由于篇幅原因,代码的其他部分已被省略。在这种情况下我将如何实现 qsort 函数?我有比较函数,但我不知道基本数组应该是什么,也不知道如何找到其他两个大小参数。预计感谢您提供的任何帮助。
最佳答案
应该是
工厂*ia = (工厂*)a;
或者您可以跳过作业并直接转换
... ((工厂 *)a)->last_name ...
我假设您在代码中的某个位置为工厂数组分配或声明了空间?
对于快速排序,您可以交换结构,也可以创建指向结构的指针数组并交换指针。
关于c - 使用qsort对结构进行排序(按 "last name"字段排序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664688/