【发布时间】: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),然后将&cmp(或简单地cmp)传递给qsort()。没有进一步检查代码... -
int (*cmp)(void *, void *);表示cmp是函数指针,而不是函数。 -
更改
qsort(p,nofl,sizeof(int), &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 显式获取函数地址不是错误,只是没有必要......