K& R哈希函数

时间:2017-12-01 10:41:01

标签: c pointers malloc sizeof

以下代码的一部分是来自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,则表示哈希表中没有安装 name ,我应该为新元素分配内存,该类型将是nlist。

但是,如果 lookup 返回NULL,基于此np = (struct nlist *) malloc(sizeof(*np)); * np将为NULL分配内存。 难道我不总是为nlist而不是* np分配内存大小吗?

1 个答案:

答案 0 :(得分: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运算符不会评估它的操作数,除非它是VLA。

引用C11,章节§6.5.3.4

  

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

相关问题