【发布时间】:2017-02-11 21:48:20
【问题描述】:
我正在尝试使用结构数组“学生”通过比较器调用 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 的比较器没有参数?当我尝试放入数组的第一个两个元素时,它也会出错。有什么想法吗?
【问题讨论】:
-
而且我们不应该理清错误消息可能与哪些行有关?抱歉,我们不是调试服务。
-
你在调用 qsort 之前声明了比较函数吗?
-
抱歉错误出现在第4行@Olaf
-
函数声明在一个包含@dromtrund的头文件中
标签: c arrays structure comparator qsort