forked from troydhanson/uthash
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest84.c
71 lines (65 loc) · 2.12 KB
/
test84.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include "uthash.h"
#include <stdio.h>
#include <stdlib.h> /* malloc */
typedef struct person_t {
char *first_name;
int id;
UT_hash_handle hh;
} person_t;
int main()
{
person_t *people=NULL, *person, *new_person, *tmp;
const char **name;
const char * names[] = { "bob", "jack", "gary", "ty", "bo", "phil", "art",
"gil", "buck", "ted", NULL
};
int id=0;
for(name=names; *name!=NULL; name++) {
person = (person_t*)malloc(sizeof(person_t));
if (person == NULL) {
exit(-1);
}
person->first_name = (char*)malloc(10UL);
if (person->first_name == NULL) {
exit(-1);
}
strcpy(person->first_name, *name);
person->id = id++;
HASH_ADD_STR(people,first_name,person);
printf("added %s (id %d)\n", person->first_name, person->id);
}
person=NULL;
person_t **p=&person;
for(name=names; *name!=NULL; name++) {
HASH_FIND_STR(people,*name,*p);
if (person != NULL) {
printf("found %s (id %d)\n", person->first_name, person->id);
new_person = (person_t*)malloc(sizeof(person_t));
if (new_person == NULL) {
exit(-1);
}
new_person->first_name = (char*)malloc(10UL);
if (new_person->first_name == NULL) {
exit(-1);
}
strcpy(new_person->first_name, person->first_name);
new_person->id = person->id*10;
HASH_REPLACE_STR(people,first_name,new_person,tmp);
printf("replaced (%c) with %s (id %d)\n", (tmp!=NULL)?'y':'n', new_person->first_name, new_person->id);
if (tmp != NULL) {
free(tmp->first_name);
free(tmp);
}
} else {
printf("failed to find %s\n", *name);
}
}
printf("traversing... \n");
HASH_ITER(hh, people, person, tmp) {
printf("%s (id %d)\n", person->first_name, person->id);
HASH_DEL(people,person);
free(person->first_name);
free(person);
}
return 0;
}