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.
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,
aandbare pointers in yourcompfunction, 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
mallocin 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
mallocfunction returns avoid *which will quite happily convert implicitly into any other pointer.Here’s a complete program with those fixes:
The output: