hash_demo.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // a word counter, it counts word frequencies from standard input
  2. // from: https://github.com/benhoyt/ht/blob/master/samples/demo.c
  3. /*
  4. $ gcc -o word_counter.out hash_demo.c hashtable.c
  5. $ echo 'foo bar the bar bar bar the' | ./word_counter.out
  6. See also:
  7. https://stackoverflow.com/questions/5134891/how-do-i-use-valgrind-to-find-memory-leaks
  8. */
  9. #include "hashtable.h"
  10. #include <ctype.h>
  11. #include <stdio.h>
  12. #include <stdlib.h>
  13. // Example:
  14. // $ echo 'foo bar the bar bar bar the' | ./word_counter
  15. // foo 1
  16. // bar 4
  17. // the 2
  18. // 3
  19. void exit_nomem(void) {
  20. fprintf(stderr, "out of memory\n");
  21. exit(1);
  22. }
  23. void accumulate_word_count(ht* counts, char* word){
  24. void* value = ht_get(counts, word); // Look up word.
  25. // Already exists, increment int that value points to.
  26. if (value != NULL) {
  27. int* pcount = (int*)value;
  28. (*pcount)++;
  29. return;
  30. }
  31. // Word not found, allocate space for new int and set to 1.
  32. int* pcount = malloc(sizeof(int));
  33. if (pcount == NULL)
  34. exit_nomem();
  35. *pcount = 1;
  36. if (ht_set(counts, word, pcount) == NULL)
  37. exit_nomem();
  38. }
  39. int main(void) {
  40. ht* counts = ht_create();
  41. if (counts == NULL)
  42. exit(-1);
  43. int year_at = 1980;
  44. ht_set(counts, "year", &year_at);
  45. ht_set(counts, "bookname", "Programming in C");
  46. ht_set(counts, "author", "Brian Kernighan and Dennis Ritchie");
  47. // Print out words and frequencies, freeing values as we go.
  48. int* year = (int*) ht_get(counts, "year");
  49. char* bookname = (char*)ht_get(counts, "bookname");
  50. char* author = (char*)ht_get(counts, "author");
  51. printf("book:%s, author:%s, year:%d\n", bookname, author, *year);
  52. ht_destroy(counts);
  53. return 0;
  54. }
  55. int main2(void) {
  56. ht* counts = ht_create();
  57. if (counts == NULL) {
  58. exit_nomem();
  59. }
  60. printf("sizeof(ht_entry): %lu\n", sizeof(ht_entry));
  61. // Read next word from stdin (at most 100 chars long).
  62. char word[101];
  63. while (scanf("%100s", word) != EOF) {
  64. accumulate_word_count(counts, word);
  65. }
  66. // Print out words and frequencies, freeing values as we go.
  67. hti it = ht_iterator(counts);
  68. while (ht_next(&it)) {
  69. printf("%s %d\n", it.key, *(int*)it.value);
  70. free(it.value);
  71. }
  72. // Show the number of unique words.
  73. printf("%d\n", (int)ht_length(counts));
  74. ht_destroy(counts);
  75. return 0;
  76. }