我的代码是仅按一个字段对结构进行排序。
奇怪的是,当长度为 8 而不是 9 时它可以工作。为什么会这样,有什么问题?
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;
}
输出是:
22 22 22 22 22 22 21 20 10
10 22 22 22 22 22 21 20 22
但是当我将长度更改为 8 时,它可以工作。