gpt4 book ai didi

c - 使用 qsort 对结构数组进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 08:47:29 24 4
gpt4 key购买 nike

#include <stdio.h>

typedef struct
{ int occurrence
char charArray[101];
}Wordy;


int comparing(const void *a, const void *b)
{
//....
}

int main(void)
{
int i=0;
Wordy array[99999];

//.....



return 0;

}

*/

这个程序从文件中读取单词,然后计算单词的出现次数。一切正常,但我认为 qsort 函数在比较函数中无法正常工作。它假设根据它的出现对 array 进行排序。 (发现它的出现是正确的。)

我的示例文本文件:

zero one
two zero
three three

输出:

Before: zero one two three 

After: one two three

(注意排序后少了0)

最佳答案

这个:

qsort(array, i, sizeof(int), comparing);

是错误的,array不是int的数组,而是Wordy的数组。当您为 qsort() 指定错误的元素大小时,结果或多或少是随机的,因为您将获得指向 int 大小的“切片”的指针Worddy 结构数组。

尝试:

qsort(array, i, sizeof array[0], comparing);

关于c - 使用 qsort 对结构数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21141250/

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