Created
May 17, 2021 15:04
-
-
Save airportyh/25859e2a469ddb15a924c04f566b9ccd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> /* strcpy */ | |
#include <stdlib.h> /* malloc */ | |
#include <stdio.h> /* printf */ | |
#include "uthash.h" | |
struct my_struct { | |
char name[10]; /* key (string is WITHIN the structure) */ | |
int id; | |
UT_hash_handle hh; /* makes this structure hashable */ | |
}; | |
int main(int argc, char *argv[]) { | |
const char *names[] = { "joe", "bob", "betty", NULL }; | |
struct my_struct *s, *tmp, *users = NULL; | |
for (int i = 0; names[i]; ++i) { | |
s = (struct my_struct *)malloc(sizeof *s); | |
strcpy(s->name, names[i]); | |
s->id = i; | |
HASH_ADD_STR(users, name, s); | |
} | |
HASH_FIND_STR(users, "betty", s); | |
if (s) printf("betty's id is %d\n", s->id); | |
/* free the hash table contents */ | |
HASH_ITER(hh, users, s, tmp) { | |
HASH_DEL(users, s); | |
free(s); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment