My code is to sort a structure by just one field.
It is strange that it works when the length is 8 but not in
9.Why is that and what is wrong?
struct node
{
int key;//I need to sort by the key
int val;
};
int comp(const void *a, const void *b)
{
return ((struct node *)a)->key > ((struct node *)b)->key;
}
int main()
{
int i;
struct node *a;
a = malloc(10 * sizeof *a);
/*I have 8 elements*/
for (i = 0; i < 6; i++)
a[i].key = 22;
a[6].key = 21;
a[7].key = 20;
a[8].key = 10;
/*Before sorting, I print it first*/
for (i = 0; i < 9; i++)
printf("%3d", a[i].key);
printf("\n");
qsort(a, 9, sizeof(struct node), comp);
/*The sorted answer*/
for (i = 0; i < 9; i++)
printf("%3d", a[i].key);
printf("\n");
free(a);
return 0;
}
Output is:
22 22 22 22 22 22 21 20 10
10 22 22 22 22 22 21 20 22
But when I change the length to 8, it works.
What do you mean by “length”?
This code is very confusing. You need to have a single well-defined idea of how many elements you’re using, and use the same everywhere. Hint: it should not be a literal number.
Also, your comparison function is wrong, it needs to return -1, 0 or 1 for elements being less than, equal to, or greater than respectively. Your function wil only return 0 or 1.