fork download
  1. #define _GNU_SOURCE
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4.  
  5. struct MyStruct {
  6. int x; int y;
  7. };
  8. int mycomp(const struct MyStruct* a, const struct MyStruct* b) {
  9. long da = a->x*a->x + a->y*a->y;
  10. long db = b->x*b->x + b->y*b->y;
  11. return da < db ? -1 : da == db ? a->x - b->x : 1;
  12. }
  13.  
  14. /* This struct avoids the issue of casting a function pointer to
  15.   * a void*, which is not guaranteed to work.
  16.   */
  17. typedef struct CompContainer {
  18. int (*const comp_func)(const struct MyStruct *, const struct MyStruct *);
  19. } CompContainer;
  20.  
  21. int delegatingComp(const void *a, const void *b, void* comp) {
  22. return ((CompContainer*)comp)->comp_func((const struct MyStruct *)a,
  23. (const struct MyStruct *)b);
  24. }
  25.  
  26. void myStructSort(
  27. struct MyStruct *arr,
  28. int size,
  29. int (*comp_func)(const struct MyStruct *,
  30. const struct MyStruct *)) {
  31. const CompContainer comp = {comp_func};
  32. qsort_r(arr, size, sizeof(struct MyStruct), delegatingComp, &comp);
  33. }
  34.  
  35. int main(void) {
  36. struct MyStruct v[] = {{1,4},{2,3},{3,2},{4,1}};
  37. myStructSort(v, 4, mycomp);
  38. for (int i = 0; i < 4; ++i) printf("{%d,%d} ", v[i].x, v[i].y);
  39. putchar('\n');
  40. return 0;
  41. }
  42.  
Success #stdin #stdout 0s 2156KB
stdin
Standard input is empty
stdout
{2,3} {3,2} {1,4} {4,1}