fork download
  1. #include <stdlib.h>
  2.  
  3. #include <stdio.h>
  4.  
  5. #include <string.h>
  6.  
  7.  
  8.  
  9. struct entry
  10.  
  11. {
  12.  
  13. char key;
  14.  
  15. const char* value;
  16.  
  17. };
  18.  
  19.  
  20.  
  21. const struct entry map[] =
  22.  
  23. {
  24.  
  25. { 'a', "a.text" },
  26.  
  27. { 'b', "b.text" },
  28.  
  29. { 'c', "c.text" },
  30.  
  31. { 'd', "d.text" },
  32.  
  33. { 'e', "e.text" }
  34.  
  35. };
  36.  
  37.  
  38.  
  39. int compare(const void* l, const void* r)
  40.  
  41. {
  42.  
  43. const struct entry* ll = (const struct entry*)l;
  44.  
  45. const struct entry* rr = (const struct entry*)r;
  46.  
  47.  
  48.  
  49. return ll->key - rr->key;
  50.  
  51. }
  52.  
  53.  
  54.  
  55. int main()
  56.  
  57. {
  58.  
  59. struct entry find = { 'd' };
  60.  
  61.  
  62.  
  63. struct entry* e = bsearch(&find,
  64.  
  65. map,
  66.  
  67. sizeof(map)/sizeof(map[0]),
  68.  
  69. sizeof(map[0]),
  70.  
  71. compare);
  72.  
  73.  
  74.  
  75. if (e)
  76.  
  77. {
  78.  
  79. printf("{%c, %s}\n", e->key, e->value);
  80.  
  81. }
  82.  
  83. else
  84.  
  85. {
  86.  
  87. printf("Not found\n");
  88.  
  89. }
  90.  
  91.  
  92.  
  93. return 0;
  94.  
  95. }
  96.  
  97.  
Success #stdin #stdout 0.01s 1720KB
stdin
Standard input is empty
stdout
{d, d.text}