因此,我try 实现了一个简单的词典,如这post中所示.但是,我确实修改了代码:
A)词典:
/* String utility for duplication */
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;
}
struct nlist {
struct nlist *next;
char *name;
char *defn;
};
#define HASHSIZE 101
struct Dict {
struct nlist *hashtab[HASHSIZE];
};
/* 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(struct Dict *d, char *s)
{
struct nlist *np;
for (np = d->hashtab[hash(s)]; np != NULL; np = np->next)
if (strcmp(s, np->name) == 0)
return np; /* found */
return NULL; /* not found */
}
struct nlist *insert(struct Dict *d, char *name, char *defn)
{
struct nlist *np;
unsigned hashval;
if ((np = lookup(d, 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 = d->hashtab[hashval];
d->hashtab[hashval] = np;
} else /* already there */
free((void *) np->defn); /*free previous defn */
if ((np->defn = strdup(defn)) == NULL)
return NULL;
return np;
}
B)示例:
int main() {
struct Dict *dtest = (struct Dict*)malloc(sizeof(struct Dict));
insert(dtest, "hello", "world");
// Look up a definition by name
struct nlist *result = lookup(dtest, "hello");
if (result != NULL) {
printf("Definition for 'hello': %s\n", result->defn);
} else {
printf("'hello' is not found in the dictionary.\n");
}
return 0;
}
当我try 调试它时,收到以下错误:
线程%1收到信号SIGSEGV,分段故障. 正在查找中的0x00007ff6bc661626(d=0x220924616e0,S=0x7ff6bc673006"Hello").c:40 40if(strcMP(S,NP-&>名称)==0)
我只是不明白简单的代码修改怎么会产生这种意想不到的行为,坦率地说,我也不确定如何go 做.