这是一个简单的C++测试代码,它将按照学生的studentId (一个整数)对结构进行排序:
#include <iostream>
using namespace std;
struct student {
int grade;
int studentId;
string name;
};
int studentIdCompareFunc(const void * student1, const void * student2);
int main()
{
const int ARRAY_SIZE = 10;
student studentArray[ARRAY_SIZE] = {
{81, 10009, "Aretha"},
{70, 10008, "Candy"},
{68, 10010, "Veronica"},
{78, 10004, "Sasha"},
{75, 10007, "Leslie"},
{100, 10003, "Alistair"},
{98, 10006, "Belinda"},
{84, 10005, "Erin"},
{28, 10002, "Tom"},
{87, 10001, "Fred"},
};
qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);
for (int i = 0; i < ARRAY_SIZE; i++)
{
cout << studentArray[i].studentId << " ";
}
}
int studentIdCompareFunc(const void * voidA, const void * voidB)
{
student* st1 = (student *) (voidA);
student* st2 = (student *) (voidB);
return st1->studentId - st2->studentId;
}它按预期打印studentId整数,但不返回零,它返回-1072740940 (0xC0000374)。
我通过将ARRAY_SIZE更改为15或增加ARRAY_SIZE参数进行了测试,但仍然得到了相同的结果。
造成这个错误的原因是什么?我该怎么解决呢?
发布于 2022-08-18 21:57:57
qsort(studentArray, ARRAY_SIZE, sizeof(student), studentIdCompareFunc);qsort是一个C库函数,它对C++类完全不了解。就像结构中的std::string对象一样,这段代码试图排序。不明确的行为,和乡下人,接踵而来。
如果这里的目的是编写C++代码,那么使用C++等效的std::sort,这是一个原生C++算法:
#include <algorithm>
// ...
std::sort(studentArray, studentArray+ARRAY_SIZE,
[]
(const auto &a, const auto &b)
{
return a.studentId < b.studentId;
});https://stackoverflow.com/questions/73409797
复制相似问题