Skip to content

Instantly share code, notes, and snippets.

@joelburton
Last active May 2, 2017 16:51
Show Gist options
  • Save joelburton/2f144fcf811afd484db592ab706dab58 to your computer and use it in GitHub Desktop.
Save joelburton/2f144fcf811afd484db592ab706dab58 to your computer and use it in GitHub Desktop.
Example of using glibc tsearch
/** Demonstration of tsearch. */
#include <search.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Node {
char *name;
int age;
} Node;
int compareNode(const void *a, const void *b) {
const Node *aa = a;
const Node *bb = b;
return strcasecmp(aa->name, bb->name);
}
void delNode(
const void *nodep, VISIT value, int level __attribute__((unused))) {
const struct Node *n = *(const Node **)nodep;
if (value == leaf || value == endorder) {
printf("killing %s\n", n->name);
free(n->name);
free((void *)n);
free((void *)nodep);
}
}
void printNode(
const void *nodep, VISIT value, int level __attribute__((unused))) {
const struct Node *n = *(const Node **)nodep;
if (value == leaf || value == postorder)
printf("%s is %i\n", n->name, n->age);
}
bool add(void **tree, char *name, int age) {
Node *mt = calloc(sizeof(Node), 1);
mt->name = strdup(name);
mt->age = age;
Node *added = tsearch(mt, tree, compareNode);
if (mt == * (Node **) added)
return true;
free(mt->name);
free(mt);
printf("(dup)\n");
return false;
}
Node *find(void *tree, char *name) {
Node *mt = calloc(sizeof(Node), 1);
mt->name = strdup(name);
Node *found = tfind(mt, &tree, compareNode);
free(mt->name);
free(mt);
return * (Node **) found;
}
int main() {
void *tree = 0;
add(&tree, "Joel", 44);
add(&tree, "Vi", 32);
add(&tree, "Bob", 15);
add(&tree, "Bob", 16);
Node *vi = find(tree, "Vi");
if (vi)
printf("found %s with %i!\n", vi->name, vi->age);
twalk(tree, printNode);
twalk(tree, delNode);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment