我正在编写这个程序,它需要在表上执行qsort()。我在互联网上做了大量的研究,但我仍然遗漏了一些东西。下面是源代码的选定部分。
#define NOSLACK __attribute__((packed))
#define TABWIDTH 100 /* width of big table */
#define TABSIZE 100 /* number of entries in big table */
struct ELEMEN
{char flags; /* flags pertaining to this task */
short int tasknum; /* number of THIS task (excluding any step number) */
short int numpre; /* number of prereqs this task has */
short int numpost; /* number of postreqs this task has */
short int prereqs[0]; /* table of prereqs (omitted if numpre = 0) */
short int postreqs[0]; /* table of postreqs (omitted if numpost = 0) */
char fragment[TABWIDTH /* fragment of the descrip- */
- sizeof(char) /* tion; as much as will fit */
- sizeof(short int) * 3];} NOSLACK;
/* the lengths of all the above fields should total to TABWIDTH */
struct ELEMEN bigtable[TABSIZE];
short int e35(const void*, const void*);
short int main(int argc, char* argv[])
qsort(g.bigtable, numelem, TABWIDTH, /* sort table using e35() */
e35); // <--- PROBLEM HERE
short int e35(const void* elem1, const void* elem2) /* sort tasks */
{return(memcmp( /* into se- */
(short int*)&((struct ELEMEN*)elem1)-> tasknum, /* quence by */
(short int*)&((struct ELEMEN*)elem2)-> tasknum, /* task number */
sizeof(short)
));问题在于对qsort()的调用。如果最后一个参数仅为e35,则会收到警告消息:警告:从不兼容的指针类型-- the兼容-指针-类型中传递‘qsort’的参数4。
如果我将e35更改为(e35)(const *)(const*),则会得到: error: const之前的预期表达式和error:函数“e35”中的参数太少
如果我将它改为e35(星号)(const*)(const*)(const*),则会得到: error:‘)’令牌错误:函数‘e35’的参数太少,而error:在‘const’之前的预期表达式
我遗漏了什么?我相信gcc并不知道e35是一个函数,而不是一个变量或数组。
我以前用过qsort(),但这是gcc治下的第一次。以前,我在TurboC下使用过它,在这里我只需要函数的名称e35。
我在Debian下用gcc编译。qsort()的目的是在以后重复搜索表,并希望能够更快地搜索该表。
(附带的问题,只是为了好玩:为什么我要调用比较例程e35?这是从哪里来的,意义是什么?也许我应该把这个问题放在“粉饰”或“回溯计算”上。)
发布于 2019-11-02 15:05:14
使用int返回。放弃不必要的施放。作为short进行比较。避免减法溢出。
int e35(const void* elem1, const void* elem2) {
const struct ELEMEN* t1 = elem1;
const struct ELEMEN* t2 = elem2;
return (t1->tasknum > t2->tasknum) - (t1->tasknum < t2->tasknum);
}https://stackoverflow.com/questions/58671997
复制相似问题