以下代码的一部分是K&R的简单哈希查找算法的实现 . lookup在表中搜索s,并返回指向找到它的位置的指针,如果不存在,则返回NULL:
struct hashElement *lookup(char *name){
struct hashElement *currentStruct;
int cmp;
for (currentStruct = hashTable[calcIndex(name)]; currentStruct; currentStruct = currentStruct->p)
if (cmp = strcmp(name, currentStruct->name) == 0)
return currentStruct;
return NULL;}
安装使用查找来确定是否已存在正在安装的名称:
struct nlist *install(char *name, char *defn)
{
struct nlist *np;
unsigned hashval;
if ((np = lookup(name)) == NULL){
np = (struct nlist *) malloc(sizeof(*np));
...}
...}
如果lookup返回NULL,则表示哈希表中没有安装名称,我应该为新元素分配内存,该类型将是nlist .
但是,基于此 np = (struct nlist *) malloc(sizeof(*np));
* np将为NULL分配内存,如果查找返回NULL . 我不应该总是为nlist而不是* np分配内存大小吗?
1 回答
如果查找返回NULL,> * np将为NULL分配内存 .
不,那不是真的 .
首先,在
the cast in not needed . 那就是说
是相同的
因为
*np
的类型是struct nlist
. 请记住,sizeof
运算符不会对它进行评估's operand unless it'是一个VLA .引用
C11
,章节§6.5.3.4