结构指针数组是否自动指向NULL /未被初始化?我认为不是,但它似乎在以这种方式在下面的代码行操作:自动指向NULL的结构指针数组?
for (np = hashtab[hash(s)]; np != NULL; np = np->next)
NP是一个结构指针,s是一个字符串。
当循环开始时,hashtab[]
中的元素都没有被初始化。每次运行程序时,循环都会立即终止,因为hashtab[]
包含NULL
完整代码如下。
struct nlist { /* table entry: */
struct nlist *next; /* next entry in chain */
char *name; /* defined name */
char *defn; /* replacement text */
};
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)
return np; /* found */
return NULL; /* not found */
}
'hashtab'是如何定义的? – 2014-09-25 18:52:54