fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <string.h>
  5.  
  6. #define COUNT(x) (sizeof(x) / sizeof(x[0]))
  7.  
  8. struct entry {
  9. const char *word;
  10. const char *def;
  11. };
  12.  
  13. int compare_entry(const void *l, const void *r)
  14. {
  15. const struct entry *ll = l;
  16. const struct entry *rr = r;
  17. return strcmp(ll->word, rr->word);
  18. }
  19.  
  20. void dump(struct entry dict[], size_t n)
  21. {
  22. for (size_t i = 0; i < n; i++) {
  23. printf("\"%s\" = \"%s\"\n", dict[i].word, dict[i].def);
  24. }
  25. }
  26.  
  27. int main()
  28. {
  29. struct entry dictionary[] = {
  30. { "def", "second entry" },
  31. { "abc", "first entry" },
  32. { "ghi", "third entry" },
  33. { "mno", "fifth entry" },
  34. { "jkl", "fourth entry" }
  35. };
  36.  
  37.  
  38. puts("Before:");
  39. dump(dictionary, COUNT(dictionary));
  40.  
  41. qsort(dictionary, COUNT(dictionary), sizeof(dictionary[0]), compare_entry);
  42.  
  43. puts("\nAfter:");
  44. dump(dictionary, COUNT(dictionary));
  45.  
  46. return 0;
  47. }
  48.  
Success #stdin #stdout 0s 1788KB
stdin
Standard input is empty
stdout
Before:
"def" = "second entry"
"abc" = "first entry"
"ghi" = "third entry"
"mno" = "fifth entry"
"jkl" = "fourth entry"

After:
"abc" = "first entry"
"def" = "second entry"
"ghi" = "third entry"
"jkl" = "fourth entry"
"mno" = "fifth entry"