I have a structure array that is created in a function locally, in order to copy to it the contents of a linked list so that they can be sorted and then printed.
How do I implement qsort in this case?
Code:
/* Initialize record structure for each soldier */
struct record {
long int aa;
char firstname[20];
char lastname[30];
struct sdate datein;
struct sdate dateout;
int freedays;
int servicedays;
} soldiers;
/* Initialize nodes for linked list */
struct node {
struct record soldier;
struct node* next;
};
And then in the function that is called when we want to sort the linked list basied on servicedays...
Code:
void servicequeue(struct node* head, int number, int countrec)
{
int i;
struct record queue[countrec];
struct node* current = head;
for (i=0;i<countrec;i++) {
queue[i] = current->soldier;
current = current->next;
}
qsort((void *) queue, countrec, sizeof (struct record), compare(queue));
printf ("Yphresia prepei na kanoun oi parakatw:\n");
for (i=0;i<number;i++) {
printf ("%s %s\n", queue[i].firstname, queue[i].lastname);
}
}
int compare(struct record queue, const void *p1, const void *p2)
{
return (((queue*)p1)->servicedays - ((queue*)p2)->servicedays);
}
...which obviously doesn't work, and it was a long shot based on a suggestion in another thread. Anyone able to help me get it right?
The example I saw didn't have any struct element in the compare function because the structure was globally declared. What should I do now that it's declared locally? I only need one tiny correction.
countrec is the number of records in the linkedlist, number is how many elements we want to show from the top after we sort.