我正在对一堆 IP 进行排序,但由于某种原因,它们的顺序错误。我不太确定问题出在哪里。
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
这就是我对它们进行排序的方式。
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);
}
任何帮助将不胜感激。谢谢
你有一个指向的指针数组mystruct
s, but qsort
使用这个比较函数将期望一个简单的数组mystruct
s。对数组进行排序mystruct*
您需要向比较函数添加另一个间接级别:
int struct_cmp(const void *a, const void *b) {
mystruct *ia = *(mystruct **)a;
mystruct *ib = *(mystruct **)b;
return strcmp(ia->ip, ib->ip);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)