I'm trying to sort the struct node by variable a, but the result turns out to be wrong.
My result:
{5, 4}, {6, 2}, {7, 3}, {4, 1}, {3, 7}, {1, 3}, {0, 0}, My code:
#include <stdio.h> #include <stdlib.h> typedef struct node { int x; int y; } n; int num = 7; int compare(const void *ele1, const void *ele2) { n *px, *py; px = (n *) ele1; py = (n *) ele2; return px->x < py->x; } int main() { n node[7] = { {4, 1}, {6, 2}, {1, 3}, {5, 4}, {7, 3}, {3, 7} }; int i; qsort(node, num, sizeof (node[0]), compare); for (i = 0; i < num; i++) printf("{%d, %d}, ", node[i].x, node[i].y); return 0; } If I sort only six pairs of elements, then the result is:
{7, 3}, {6, 2}, {5, 4}, {4, 1}, {1, 3}, {0, 0}, which is correct, but when I tried with seven, it shows the results above. Does anyone know why that happens? Thanks!