【问题标题】:passing argument 4 of qsort from incompatible pointer type从不兼容的指针类型传递 qsort 的参数 4
【发布时间】:2016-01-27 09:29:15
【问题描述】:

请帮助解决这个警告:

从不兼容的指针类型传递 qsort 的参数 4;

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BSIZE 200
int (*cmp)(void *, void *);
int main(int argc, char *argv[]){

  FILE *in;
  char buf[BSIZE];
  int i, nofl;
  char *p[20];



  if(argc<2){
    printf("too few parameters...\n");
    return 1;
}
  in=fopen(argv[1], "r+b");
  if(in == NULL){
    printf("can't open file: %s\n", argv[1]);
    return 0;
}

  while(fgets(buf,BSIZE+1,in)){
    p[i]=malloc(strlen(buf)+1);
    strcpy(p[i],buf);

    i++;
}

  nofl=i;

  qsort(p,nofl,sizeof(int), &cmp);

  for(i=0;i<nofl;i++)
    printf("%s\n",p[i]);

  return 0;
}

int (*cmp)(void *a, void *b){
  int n1 = atoi(*a);
  int n2 = atoi(*b);
  if (n1<n2)
    return -1;
  else if (n1 == n2)
    return 0;
  else
    return 1;
}

我认为这个 c 程序必须将字符串转换为 int 并按 asc 排序。问题是,使用 qsort strngs mass 无效,它与未排序保持相同。

【问题讨论】:

  • 函数指针不是这样工作的。将cmp 声明并定义为int cmp(const void *a, const void *b),然后将&amp;cmp(或简单地cmp)传递给qsort()。没有进一步检查代码...
  • int (*cmp)(void *, void *); 表示cmp 是函数指针,而不是函数。
  • 更改qsort(p,nofl,sizeof(int), &amp;cmp); --> qsort(p,nofl,sizeof(int), cmp); 也更改int (*cmp)(void *a, void *b) --> int cmp(void *a, void *b)
  • void *a, void *b){ int n1 = atoi(*a); 将不起作用,因为 *a 正在取消引用 void *
  • @WeatherVane 显式获取函数地址不是错误,只是没有必要......

标签: c strcmp qsort


【解决方案1】:
int (*cmp)(void *a, void *b){ ... }

不是定义函数的合法代码。

代替

int (*cmp)(void *, void *);

使用

int cmp(const void*, const void*);

更新,以回应 OP 的评论

int cmp(const void *a, const void *b){

  // Here, a is really a pointer to a `char*`.

  const char* pa = *(const char**)a;
  const char* pb = *(const char**)b;

  int n1 = atoi(pa);
  int n2 = atoi(pb);

  // Simplify the return value.
  return ((n1 > n2) - (n1 < n2));

  /***
  if (n1<n2)
    return -1;
  else if (n1 == n2)
    return 0;
  else
    return 1;
  ***/

}

【讨论】:

  • 谢谢你,现在我没有任何警告。我已经改变了函数定义,因为你很难过。
    int (*cmp)(void *a, void *b){ int n1 = atoi(*a); int n2 = atoi(*b);如果(n1<n2 n2></n2> qsort 不工作 当我打印 strng[i] 大量元素时,没有任何变化
  • @wakajawaka,你有没有注意到任何改进?
  • 它没有给我任何警告。排序不起作用。它给了我同样的结果。什么都没有改变
  • OP 的原始比较 if (n1&lt;n2) return -1;.... 没有像 return ( n1 - n2); 这样的溢出问题 惯用替代:(n1&gt;n2) - (n1&lt;n2)
  • int n1 = atoi(*(char **)a); int n2 = atoi(*(char **)b);
猜你喜欢
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 2016-03-28
相关资源
最近更新 更多