c - K&R哈希函数

标签 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的新元素分配内存。

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

最佳答案

*np will allocate memory for NULL if lookup return 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 章

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

关于c - K&R哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47591596/

相关文章:

c - 链表和指针的问题(C)

c - 我应该如何定义/声明字符串常量

swift - 指针取消引用 Swift

c - 使用 SDL_strdup 和类似工具获取文件名时出现问题

c - 持久化malloc创建的内存块

c - 使用 #defines 时得到的结果不同

c - 从头开始为 Linux 构建 Glibc-2.11.1 时出错

c - C中指针的变量赋值

c - 如何从数组中打印出指针指向的值

c - 关于malloc的问题