Skip to content

Instantly share code, notes, and snippets.

@ctrlcctrlv
Created April 26, 2021 11:22
Show Gist options
  • Select an option

  • Save ctrlcctrlv/40267bf7d18876294780c8e2f149ab96 to your computer and use it in GitHub Desktop.

Select an option

Save ctrlcctrlv/40267bf7d18876294780c8e2f149ab96 to your computer and use it in GitHub Desktop.
Example of using functions in search.h
// gcc -g -O0 -lm -o /tmp/search_example /tmp/search_example.c
#define _GNU_SOURCE
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <search.h>
int main(int argc, char* argv[]) {
// Create a hash table with 255 entries.
struct hsearch_data* htable = malloc(sizeof(struct hsearch_data*));
hcreate_r(255, htable);
// Insert pow(i,i) for i in range(0..255) inclusive into hash table.
// Key is `i as char`, therefore 255 is maximum for this method of key derivation.
for (int i = 0; i <= 255; i++) {
// ENTRY type is defined in search.h
ENTRY item;
char* key = malloc(2);
key[0] = i;
item.key = key;
double* data = calloc(1, sizeof(double));
// Set void* item.data to double* data
*data = (pow((double)i,(double)i)); item.data = data;
ENTRY* unused; hsearch_r(item, ENTER, &unused, htable);
}
// Pointer to found entry
ENTRY* found;
ENTRY search;
search.key = "\x8";
hsearch_r(search, FIND, &found, htable);
printf("found %f\n", *(double*)(found->data));
search.key = "\xff";
hsearch_r(search, FIND, &found, htable);
printf("found %f\n", *(double*)(found->data));
hdestroy_r(htable);
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment