I'm sorting a bunch of IPs, but for some reason they come in the wrong order. I'm not quite sure where could be the problem.
66.249.71.3
190.148.164.245
207.46.232.182
190.148.164.245
190.148.164.245
202.154.114.253
190.148.164.245
190.148.164.245
66.249.71.3
190.148.164.245
202.154.114.253
Here it is the way Im sorting them.
typedef struct {
char *ip;
} mystruct;
/* qsort */
int struct_cmp(const void *a, const void *b)
{
mystruct *ia = (mystruct *)a;
mystruct *ib = (mystruct *)b;
return strcmp(ia->ip, ib->ip);
}
...
qsort(a_struct, 11, sizeof(mystruct*), struct_cmp);
for(..){
printf("%s\n",a_struct[i]->ip);
}
Any help will be appreciate it. Thanks
You have an array of pointers to mystructs, but qsort with this comparision function would expect a simple array of mystructs. To sort an array of mystruct* you need to add another level of indirection to the comparison function:
int struct_cmp(const void *a, const void *b) {
mystruct *ia = *(mystruct **)a;
mystruct *ib = *(mystruct **)b;
return strcmp(ia->ip, ib->ip);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With