本文介绍了结构 - 分选C-字符串的qsort的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在整理一堆IP地址,但由于某种原因,他们在错误的顺序。我不太清楚的地方可能是问题。
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);
}
任何帮助将AP preciate它。谢谢
Any help will be appreciate it. Thanks
推荐答案
您已经指针到 MYSTRUCT
数组S,但的qsort
这个比较函数期望 MYSTRUCT
s的简单数组。排序 MYSTRUCT *数组
你需要间接的另一个层次添加到比较功能:
You have an array of pointers to mystruct
s, but qsort
with this comparision function would expect a simple array of mystruct
s. 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);
}
这篇关于结构 - 分选C-字符串的qsort的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!