cole cole - 1 year ago 87
C Question

QuickSort in C library

The Second Param of qsort

Now I want to sort a set of points by x.Following is my code:

typedef struct {
int x;
int y;
} point;

int cmpfunc( const void * a, const void * b){
point *point1 = (point *)(a);
point *point2 = (point *)(b);

if(point1->x < point2->x){
return -1;
return 0;

int main(){

point *points = (point *)malloc(sizeof(point)*3);
points[0].x = 1;
points[0].y = 2;

points[1].x = 0;
points[1].y = 4;

points[2].x = 4;
points[2].y = 3;


int i=0;
while (i<3){
return 0;

Please notice qsort(points,2,(sizeof(points[0])),cmpfunc);

The result is correct when I pass the second param value
.What's wrong with my code?

Answer Source

To sort on the x axis, you need something like:

static void cmpfunc(const void *a, const void *b)
  const point *pa = a, *pb = b;
  return pa->x < pb->x ? -1 : pa->x > pb->x;

It must return less than, equal to, or greater than zero. See the manual page for more.

Oh, and you really shouldn't "drop const" like that, for no reason, and of course you never need to cast from void * to a pointer to struct like we have here. Keep it simple, and learn these things so you don't feel a need to "throw in a cast for good measure".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download