gpt4 book ai didi

c - struct - 使用 qsort 对 c 字符串进行排序

转载 作者:行者123 更新时间:2023-12-01 16:08:42 25 4
gpt4 key购买 nike

我正在对一堆 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,但是 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);
}

关于c - struct - 使用 qsort 对 c 字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1806541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com