Reputation: 1
please help with this warning:
passing argument 4 of qsort from incompatible pointer type;
#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;
}
i think this c program must convert string to int and sort by asc. the problem is that with qsort strngs massive takes no effect, it stays the same as unsorted.
Upvotes: 0
Views: 2041
Reputation: 206737
int (*cmp)(void *a, void *b){ ... }
is not legal code to define a function.
Instead of
int (*cmp)(void *, void *);
use
int cmp(const void*, const void*);
Update, in response to comment by 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;
***/
}
Upvotes: 2