gpt4 book ai didi

比较器未在 qsort 中调用 [错误 : expected expression before comparator]

转载 作者:行者123 更新时间:2023-11-30 16:50:32 26 4
gpt4 key购买 nike

我正在尝试使用结构数组“student”通过比较器调用 qsort它具有以下属性:

typedef struct
{
int ID; // 4 bytes = 164 [+ int]
char firstname[NAME_LENGTH]; // 1 bytes * length (80) = 160 [2 * NAME_LENGTH]
char lastname[NAME_LENGTH]; // 1 bytes * length (80)
} Student;

我的代码尝试从函数调用 qsort 3 次:按 ID 排序,然后按名字排序,然后按姓氏排序。主函数负责调用其他函数进行读写。找到一个函数中的错误应该使我能够将其应用到另一个函数中,对吧?然而,涉及排序的函数是:

#ifdef TEST_SORTID
void StudentSortbyID(Student * stu, int numelem)
{
qsort(&(stu-> ID), numelem, sizeof(stu), compareInts);
}
#endif

#ifdef TEST_SORTFIRSTNAME
void StudentSortbyFirstName(Student * stu, int numelem)
{
qsort(&(stu-> firstname), numelem, sizeof(stu), compareStrings);
}
#endif

#ifdef TEST_SORTLASTNAME
void StudentSortbyLastName(Student * stu, int numelem)
{
qsort(&(stu-> lastname), numelem, sizeof(stu), compareStrings);
}
#endif

#ifdef TEST_COMPAREINTS
int compareInts(const void * argu1, const void * argu2)
{
const int * iptr1 = (const int *) argu1; //convert void to integer pointer
const int * iptr2 = (const int *) argu2;
int ival1 = * iptr1; //convert pointer to value
int ival2 = * iptr2;
if(ival1 < ival2) { return -1; } //return -1 if first value is less
if(ival1 > ival2) { return 1; } //return 1 if previous value is greater
if(ival1 == ival2) { return 0; } //return 0 if the adjacent values are equal
}
#endif

#ifdef TEST_COMPARESTRINGS
int compareStrings(const void * argu1, const void * argu1)
{
//String is an array of characters (string = char*) -> pointing to string
const char * const * sptr1 = (const char * *) argu1; //converting empty pointers to strings which point to characters [**]
const char * const * sptr2 = (const char * *) argu2;
const char * string1 = * sptr1; // a string is a character pointer
const char * string2 = * sptr2;
return strcmp(string1,string2);
}
#endif

运行 gcc 时遇到的错误是:

student.c:120: error: too few arguments to function ‘compareInts’

我以为 qsort 的比较器没有接受参数?当我尝试放入数组的前两个元素时,它也会出错。有什么想法吗?

最佳答案

我建议一个接一个地解决问题,即从按 ID 排序开始,提供特定的“sortStudentById”比较器函数,并从没有任何 #ifdef 的代码开始(这些通常会使调试和理解编译器错误变得更加复杂)。

我想原因之一是您的比较函数在 qsort 中使用之前没有声明。

一旦解决了这个问题,您在使用qsort时肯定会遇到下一个问题。如果要对学生对象进行排序,则比较函数需要获取指向学生对象的指针(而 qsort 将重复交换整个学生对象,而不是指向它们的指针)。将指向成员的指针传递给 qsort(如 &(stu-firstname))将使 qsort 以肯定不符合预期的方式交换内容。

尝试以下代码作为起点,并根据需要进行调整:

int compareStudentsByID(const void* s1, const void *s2) {
return ((Student *)s1)->ID - ((Student*)s2)->ID;
}

void sortByID(Student *s) {

qsort(s,100,sizeof(Student),compareStudentsByID);
}

int main() {

Student students[100];
for (int i=0; i<100; i++) {
students[i].ID = rand()%1000;
}
sortByID (students);

return 0;
}

关于比较器未在 qsort 中调用 [错误 : expected expression before comparator],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42181622/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com