在 C 中编译哈希 table 实现时出错

Error compiling hash table implementation in C

我有一个包含约 600 万条记录(键值对)的文件,我试图将其存储在哈希 table 中。但是,我在第一道篱笆上摔倒了。该程序无法编译,我什至还没有尝试读取记录。

首先,在尝试初始化整个数组时出现以下错误:

31: error: incompatible types when assigning to type ‘struct node’ from type ‘void *’ 

也许我应该使我的结构节点中的所有内容都等于 null?但是数组位置等于null不是更好吗?

此外,在我的插入函数中,当检查数组位置是否为 null 时,出现此错误:

invalid type argument of unary ‘*’ (have ‘struct node’)

如何检查数组位置是否为空?此错误来自第 63、65、69、71、76 行

我在这里阅读了很多帖子(包括 Why whole structure can not be compared in C, yet it can be copied?),但无法编译我的代码。抱歉,如果这是基本的东西。

我目前拥有的完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define HASH_SIZE 1000000


struct node{

    unsigned long long key;
    float value;
    struct node *next;
};

struct node *ebv_hash = NULL;

unsigned long long hash(unsigned long long);
void insert(unsigned long long, float);


int main(int argc, char *argv[]){

    FILE *ebv_fp;

    ebv_fp=fopen(argv[1], "r");

    ebv_hash = malloc(HASH_SIZE * sizeof(struct node));
    for(unsigned long long a=0; a <=HASH_SIZE; a++){
        *ebv_hash[a]=NULL;
    }   

    /* Code to read in data I have not written yet */

    fclose(ebv_fp);


    free(ebv_hash);

    return 0;
}


unsigned long long hash(unsigned long long ani_id){

    return (ani_id % HASH_SIZE);
}


void insert(unsigned long long nkey, float nvalue){

    struct node *nani = malloc(sizeof(struct node));
    unsigned long long hash_ind; 

    nani->key=nkey;
    nani->value=nvalue;
    nani->next=NULL;

    hash_ind = hash(nkey);

    if(ebv_hash[hash_ind] == NULL){

        ebv_hash[hash_ind] = nani;

    }else{ 
        struct node *p = malloc(sizeof(struct node));
        p = ebv_hash[hash_ind];

        while(p->next != NULL){

            p = p->next;        

        }
        p->next = nani;
    }
}

您已声明

struct node* ebv_hash = NULL;

并使用

ebv_hash = malloc(HASH_SIZE * sizeof(struct node));

这意味着您将获得 struct node.

的数组

我想你想要的是一个指向struct node的指针数组。看起来像这样:

struct node** ebv_hash = NULL;
ebv_hash = malloc(HASH_SIZE * sizeof(struct node*));
for(int i=0;i<HASH_SIZE;i++)
  ebv_hash[i] = NULL;

然后当你需要一个节点i时,你malloc自己一个并设置合适的ebv_hash[i]