[英]Using qsort To Sort Array Of Structs
#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;
}
*/
This program reads words from a file, then the occurrence of the word is calculated. 该程序从文件中读取单词,然后计算单词的出现次数。 Everything works, but I don't think the qsort function is working correctly in the comparing function.
一切正常,但我认为qsort功能在比较功能中没有正常工作。 It's suppose to sort
array
in terms of its occurrence. 假设根据数据的出现对
array
进行排序。 (Finding its occurrence is correct.) (发现它的发生是正确的。)
My sample text file: 我的示例文本文件:
zero one
two zero
three three
Output: 输出:
Before: zero one two three
After: one two three
(notice that zero is missing after sorting) (注意排序后零缺失)
This: 这个:
qsort(array, i, sizeof(int), comparing);
is wrong, array
is not an array of int
, it's an array of Wordy
. 错了,
array
不是int
数组,它是一个Wordy
数组。 When you specify the wrong element size to qsort()
, the results are more or less random since you're going to get pointers into int
-sized "slices" of the Wordy
struct array. 当你为
qsort()
指定错误的元素大小时,结果或多或少是随机的,因为你将获得指向Wordy
结构数组的int
-sized“切片”的指针。
Try: 尝试:
qsort(array, i, sizeof array[0], comparing);
Is it because your printf
statements are different? 是因为你的
printf
语句有所不同吗? word
and charArray
ordered differently. word
和charArray
命令不同。
Before: 之前:
array[0].charArray, array[1].word, array[2].charArray, array[3].charArray); array [0] .charArray,array [1] .word, array [2] .charArray,array [3] .charArray);
After: 后:
array[0].word, array[1].charArray, array[2].charArray, array[3].charArray); array [0] .word,array [1] .charArray, array [2] .charArray,array [3] .charArray);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.