#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>

struct MyStruct {
	int x; int y;
};
int mycomp(const struct MyStruct* a, const struct MyStruct* b) {
	long da = a->x*a->x + a->y*a->y;
	long db = b->x*b->x + b->y*b->y;
	return da < db ? -1 : da == db ? a->x - b->x : 1;
}

    /* This struct avoids the issue of casting a function pointer to
     * a void*, which is not guaranteed to work.
     */
    typedef struct CompContainer {
       int (*const comp_func)(const struct MyStruct *, const struct MyStruct *);
    } CompContainer;

    int delegatingComp(const void *a, const void *b, void* comp) {
      return ((CompContainer*)comp)->comp_func((const struct MyStruct *)a,
                                               (const struct MyStruct *)b);
    }
    
    void myStructSort(
                  struct MyStruct *arr,
                  int size,
                  int (*comp_func)(const struct MyStruct *,
                              const struct MyStruct *)) {
      const CompContainer comp = {comp_func};
      qsort_r(arr, size, sizeof(struct MyStruct), delegatingComp, &comp);
    }

int main(void) {
    struct MyStruct v[] = {{1,4},{2,3},{3,2},{4,1}};
    myStructSort(v, 4, mycomp);
	for (int i = 0; i < 4; ++i) printf("{%d,%d} ", v[i].x, v[i].y);
	putchar('\n');
	return 0;
}
