-
Notifications
You must be signed in to change notification settings - Fork 0
/
c_dict.c
130 lines (117 loc) · 2.86 KB
/
c_dict.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#define HASHSIZE 3
struct nlist { /* table entry: */
struct nlist *next; /* next entry in chain */
char *name; /* defined name */
char *defn; /* replacement text */
};
static struct nlist *hashtab[HASHSIZE]; /* pointer table */
struct nlist *lookup(char *s);
struct nlist *install(char *name, char *defn);
char *strdup(char *);
unsigned hash(char *s);
/* hash: form hash value for string s */
unsigned hash(char *s)
{
unsigned hashval;
for (hashval = 0; *s != '\0'; s++)
{
hashval = *s + 31 * hashval;
}
return hashval % HASHSIZE;
}
/* lookup: look for s in hashtab */
struct nlist *lookup(char *s)
{
struct nlist *np;
for (np = hashtab[hash(s)]; np != NULL; np = np->next)
{
if (strcmp(s, np->name) == 0)
{
printf("hit: %s!\n",s);
return np; /* found */
}
printf("miss: %s!\n", s);
}
return NULL; /* not found */
}
/* install: put (name, defn) in hashtab */
struct nlist *install(char *name, char *defn)
{
struct nlist *np;
unsigned hashval;
if ((np = lookup(name)) == NULL)
{ /* not found */
np = (struct nlist *) malloc(sizeof(*np));
if (np == NULL || (np->name = strdup(name)) == NULL)
return NULL;
hashval = hash(name);
np->next = hashtab[hashval];
hashtab[hashval] = np;
}
else
{
/* already there */
free((void *) np->defn); /*free previous defn */
}
if ((np->defn = strdup(defn)) == NULL)
{
return NULL;
}
return np;
}
char *strdup(char *s) /* make a duplicate of s */
{
char *p;
p = (char *) malloc(strlen(s)+1); /* +1 for ’\0’ */
if (p != NULL)
{
strcpy(p, s);
}
return p;
}
int main()
{
struct nlist *found = NULL;
printf("***************install******************\n");
install("start","first");
install("start1","second");
install("start2","third");
install("start3","fourth");
install("start4","fifth");
install("start5","sixth");
printf("***************lookup******************\n");
found = lookup("start");
if (found)
{
printf("name: %s\ndef: %s\n", found->name, found->defn);
}
found = lookup("start1");
if (found)
{
printf("name: %s\ndef: %s\n", found->name, found->defn);
}
found = lookup("start2");
if (found)
{
printf("name: %s\ndef: %s\n", found->name, found->defn);
}
found = lookup("start3");
if (found)
{
printf("name: %s\ndef: %s\n", found->name, found->defn);
}
found = lookup("start4");
if (found)
{
printf("name: %s\ndef: %s\n", found->name, found->defn);
}
found = lookup("start5");
if (found)
{
printf("name: %s\ndef: %s\n", found->name, found->defn);
}
return 0;
}