Saturday, May 22, 2010

C Programming: qsort?

OK... I have a pointer to an array of structures with various different properties... for instance a name and an integer.





How do I use qsort to sort by number?





What I'm doing now:





qsort(Structure[N]-%26gt;Number, N, sizeof(*N), SortFunction);





It says that arument 1 makes a pointer from an integer without a cast. How do I solve this problem?

C Programming: qsort?
the argument for qsort has to be the base structure. You can't reference an item inside the structure.





Your qsort call needs to be:





qsort((void*)structureArray, numberOfStructuresInArray,


sizeOf(Structure), SortFunction);





Your sort function needs to be:





int SortFunction (const void * a, const void * b)


{





return ((Structure*)a-%26gt;Number - (Structure*)b-%26gt;Number );


}





The sort function and qsort must deal with the entire structure, not a part of it. Does that make sense?





E-mail if not... jon at j-phi.com.
Reply:In my early days, I used to write progs for the Atari using various forms of Basic. Sorts - according to size - were either Q Sort or bubble.





I tried hard to get on with C++, but after basic, it was too much hard work.





No help with your problem - just added for interest.!


No comments:

Post a Comment