Advertisement
joric

15-line hash table

Apr 3rd, 2020
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.92 KB | None | 0 0
  1. #include <stdlib.h>
  2. #define SIZE 1024
  3. static int (**hnew())[2] {
  4.     return calloc(sizeof(int**), SIZE);
  5. }
  6. static void hdel(int (**e)[2]) {
  7.     for (int i = 0; i < SIZE; i++) free(e[i]); free(e);
  8. }
  9. static int (**hget(int (**t)[2], int k))[2] {
  10.     for (int h = k & (SIZE - 1); **t && ***t != k; h = ((h + 1) & (SIZE - 1)), t += h);
  11.     return t;
  12. }
  13. static void hset(int (**t)[2], int k, int v) {
  14.     for (int (**a)[2] = hget(t, k); !*a && (*a=malloc(sizeof(**t))); (**a)[0]=k,(**a)[1]=v);
  15. }
  16.  
  17. // TEST DRIVER
  18. #include <stdio.h>
  19. int main() {
  20.     int (**table)[2] = hnew();
  21.  
  22.     hset(table, 10, 20);
  23.     hset(table, 20, 30);
  24.     hset(table, 30, 40);
  25.  
  26.     int (**a)[2] = hget(table, 10);
  27.     int (**b)[2] = hget(table, 20);
  28.     int (**c)[2] = hget(table, 30);
  29.  
  30.     printf("%d:%d\n", (**a)[0], (**a)[1]);
  31.     printf("%d:%d\n", (**b)[0], (**b)[1]);
  32.     printf("%d:%d\n", (**c)[0], (**c)[1]);
  33.  
  34.     hdel(table);
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement