C 数组使用 qsort 排序?
我已经被困在这个问题上有一段时间了,似乎没有任何效果。
我有一个数据结构:
DATA
{
int size;
int id;
}
我有一个数据结构数组:
myArray = (DATA *) malloc(10 * sizeof(DATA));
然后我分配一些测试值:
myArray[0].size = 5;
myArray[1].size = 9;
myArray[2].size = 1;
myArray[3].size = 3;
所以我的起始数组应该如下所示:
5,9,1,3,0,0,0,0,0,0
然后,我调用 qsort(myArray,10,sizeof(DATA),comp)
其中 comp 是:
int comp(const DATA * a, const DATA * b)
{
return a.size - b.size;
}
相信我,我用比较函数尝试了很多东西,但似乎没有任何效果。我只是从来没有得到任何有意义的排序。
I have been stuck on this for a while and nothing seems to work.
I have a data structure:
DATA
{
int size;
int id;
}
And I have an array of DATA structures:
myArray = (DATA *) malloc(10 * sizeof(DATA));
Then I assign some test values:
myArray[0].size = 5;
myArray[1].size = 9;
myArray[2].size = 1;
myArray[3].size = 3;
So my starting array should look like:
5,9,1,3,0,0,0,0,0,0
Then, I call qsort(myArray,10,sizeof(DATA),comp)
Where comp is:
int comp(const DATA * a, const DATA * b)
{
return a.size - b.size;
}
And trust me, I tried many things with the compare function, NOTHING seems to work. I just never get any sorting that makes any sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,它确实不会,至少不能保证。
如果您希望其中有零,可以使用 calloc() 将所有内容清零,或者自己将它们放入。
malloc()
将为您提供一个具有所需大小且内容不确定的块。换句话说,它很可能事先就拥有了记忆中的任何垃圾。而且,最重要的是,
a
和b
是comp
函数中的指针,您应该使用 < code>-> 而不是.
并且使用正确的原型进行转换是一种很好的形式。最后一点:请不要在 C 中转换
malloc
的返回值 - 如果您不小心忘记包含相关的头文件并且您的整数与指针不兼容,您可能会遇到问题。malloc
函数返回一个void *
,它会很高兴地隐式转换为任何其他指针。这是包含这些修复的完整程序:
输出:
No, it really won't, at least it's not guaranteed to.
If you want zeros in there, either use
calloc()
to zero everything out, or put them in yourself. Whatmalloc()
will give you is a block of the size required that has indeterminant content. In other words, it may well have whatever rubbish was in memory beforehand.And, on top of that,
a
andb
are pointers in yourcomp
function, you should be using->
rather than.
and it's good form to use the correct prototype with casting.And a final note: please don't cast the return from
malloc
in C - you can get into problems if you accidentally forget to include the relevant header file and your integers aren't compatible with your pointers.The
malloc
function returns avoid *
which will quite happily convert implicitly into any other pointer.Here's a complete program with those fixes:
The output: