Question:
How to use qsort function in stdlib.h ?
seed of eternity
2007-07-07 22:15:11 UTC
/*In the file stdlib.h, I find this procedure*/

_CRTIMP void __cdecl qsort(void *, size_t, size_t, int (__cdecl *)
(const void *, const void *));

/*which is why I think that this is actually a command to quick sort some kind of struct.
If there is a struct defined like below*/

struct DataBase
{ int Value;
char Name[20],Address[20];
float A,B,C;
} *VData;

void main(void)
{ int NumOfData;
NumOfData=TakeDataFromFile
(VData,"DataFile.txt");

????

WriteSortedData
(NumOfData,VData,"SortedData.txt");
}

/*Please write on the ???? how to sort the struct using the qsort procedure in the stdlib.h
Please also tell me if I have to make some kind of procedure outside the void main(void) */
Four answers:
swami060
2007-07-08 05:48:07 UTC
The qsort() is a generic function to sort any array. Let's assume that in the given structure you would like to sort on Name. Just incase two people have the same name you would like to sort on Value.



You need to write a custom compare function that would implement the above logic.



// Function to compare two DataBase elements.

int DataBaseCmp(const void *elem1, const void *elem2) {

// Typecast elements back to DataBase* type from void*

Database *dbelem1 = (const Database *)elem1;

Database *dbelem2 = (const Database *)elem2;

int diff;

// Compare names

diff = strcmp(dbelem1->Name, dbelem2->Name);

// If names are same, compare values

if( diff == 0 ) {

return dbelem1->Value - dbelem2->Value;

}

else {

return diff;

}

}



== qsort signature ==

void qsort(

void *base,

size_t num,

size_t width,

int (__cdecl *compare )(const void *, const void *)

);

=================

qsort(VData, NumOfData, sizeof(Database), DataBaseCmp);
?
2016-11-08 15:57:04 UTC
it appears that evidently that mystrcmp() gets a pointer to the array ingredient (char**), yet you desire to deliver the pointer to the string to strcmp(), rather of the pointer to the array ingredient. That hyperlink above shows you the thank you to try this. you may desire to apply double information. that is an identical with the integer occasion. The evaluate function gets a pointer to the integer, not the actual integer. bear in mind that your manipulating the array, which demands using information to the climate. If i'm getting the pointer to the string, whoopee-doo, that would not enable me to change the information interior the array.
Tuhuo
2007-07-08 02:09:26 UTC
If we have DataBase itemA and itemB, under what condition itemA is less than itemB? Sort by value, by name or by address? You should define this first.
csanon
2007-07-08 09:30:29 UTC
http://www.cppreference.com/stdother/qsort.html



Generally,searching on Google proves to be very useful.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...