首页 文章

K&R哈希函数

提问于
浏览
2

以下代码的一部分是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 回答

  • 1

    如果查找返回NULL,> * np将为NULL分配内存 .

    不,那不是真的 .

    首先,在

    np = (struct nlist *) malloc(sizeof(*np));
    

    the cast in not needed . 那就是说

    np = malloc(sizeof(*np));
    

    是相同的

    np = malloc(sizeof(struct nlist));
    

    因为 *np 的类型是 struct nlist . 请记住, sizeof 运算符不会对它进行评估's operand unless it'是一个VLA .

    引用 C11 ,章节§6.5.3.4

    sizeof运算符产生其操作数的大小(以字节为单位),该操作数可以是表达式或类型的带括号的名称 . 大小由操作数的类型确定 . 结果是整数 . 如果操作数的类型是可变长度数组类型,则计算操作数;否则,不评估操作数,结果是整数常量 .

相关问题