c - 如何使用 qsort 对结构数组进行排序
问题描述
它应该按姓氏的字母顺序对学生进行排序。我试图用 qsort 来做,但它不起作用。
struct student {
char name[30];
char lastName[30];
char grades[30][5];
int numberOfGrades;
};
int compare(const void *a, const void *b) {
struct group *s1 = (struct group *)a;
struct group *s2 = (struct group *)b;
return strcmp(s1->lastName, s2->lastName);
}
int main()
{
struct student group[30];
group[0].lastName = "Malaska";
group[1].lastName = "Kowalski";
group[2].lastName = "Adamczyk";
group[3].lastName = "Bakiewicz";
int numberOfStudents = 4;
qsort(group, numberOfStudents, sizeof(group), compare);
}
解决方案
以下是对您的代码的修改,并带有更正和注释:
struct student {
char name[30];
char lastName[30];
char grades[30][5];
int numberOfGrades;
};
//Note, error incomplete type occurs
//when using `struct group *s1 = (struct group *)a;`
//will replace with `struct student`
int compare(const void *a, const void *b) {
const struct student *s1 = (struct student *)a;
const struct student *s2 = (struct student *)b;
return strcmp(s1->lastName, s2->lastName);
}
int main()
{
struct student group[30];//local scope, will not be recognized in 'compare()'
strcpy(group[0].lastName, "Malaska");//string assignments need to use strcpy or similar, not =
strcpy(group[1].lastName, "Kowalski");
strcpy(group[2].lastName, "Adamczyk");
strcpy(group[3].lastName, "Bakiewicz");
int numberOfStudents = 4;
//sending correct size of each element
qsort(group, numberOfStudents, sizeof(group[0]), compare);
// ^^^^^^^^^^^^^^^^^
}
以下也是对您的代码的改编,但有一些额外的更改来构建,如果在您所学习的范围内,应该提供更多关于可读性、范围使用、使用typedef
以及动态内存分配和释放的示例。 ..
typedef struct { //use of `typedef struct {` rather than 'struct name {`
char name[30];
char lastName[30];
char grades[30][5];
int numberOfGrades;
}student_s; //new type, can be used in place of `struct student` anywhere.
int compare(const void *a, const void *b) {
const student_s *s1 = (student_s *)a;
const student_s *s2 = (student_s *)b;
return strcmp(s1->lastName, s2->lastName);
}
int main()
{
int numberOfStudents = 4;//moved to top so can use group
//to properly size instances of group
//dynamic memory allocation, and clean up at bottom
student_s *group = calloc(numberOfStudents, sizeof *group);
if(group)//test here to ensure success
{
strcpy(group[0].lastName, "Malaska");
strcpy(group[1].lastName, "Kowalski");
strcpy(group[2].lastName, "Adamczyk");
strcpy(group[3].lastName, "Bakiewicz");
qsort(group, numberOfStudents, sizeof(group[0]), compare);
//... more code as necessary
//when finished with 'group', free it.
free(group);
}
}
推荐阅读
- python - update QStyle in EnterEvent
- java - Thymeleaf Spring 5 在 web-inf 中找不到 html 模板
- javascript - 我正在运行的脚本退出了。我正在尝试从手机上传图片,但已停止工作
- c - 从结果类型为“void *”的函数返回“int”的不兼容整数到指针转换
- swiftui - SwiftUI 初学者:如何正确使用 didSet?
- numpy - y 事件后返回 x 的正态分布函数
- google-sheets - 将数字输入转换为 Google 表格中的字符
- python - 在 Carnets Plus 中打开数据集
- python - 如何在 python 中对齐 print()
- php - 如何从 db 获取数据到 Laravel 8 中的布局。 *