首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用qsort()函数

调用qsort()函数
EN

Stack Overflow用户
提问于 2019-11-02 14:28:08
回答 1查看 188关注 0票数 0

我正在编写这个程序,它需要在表上执行qsort()。我在互联网上做了大量的研究,但我仍然遗漏了一些东西。下面是源代码的选定部分。

代码语言:javascript
复制
#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?这是从哪里来的,意义是什么?也许我应该把这个问题放在“粉饰”或“回溯计算”上。)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-02 15:05:14

使用int返回。放弃不必要的施放。作为short进行比较。避免减法溢出。

代码语言:javascript
复制
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);
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58671997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档