将节点添加到哈希表

时间:2014-11-15 23:51:48

标签: c

当我试图将我的节点添加到哈希表时,我遇到了seg错误。我已经使用了gdb,但无法确定我为何会收到此错误。

int symbol_add (sym_table_t* symTab, const char* name, int addr) {
  int hash = 0;
  int index = 0;    
  if(symbol_search(symTab, name, &hash, &index) == NULL){
    struct node pointer = calloc (1,sizeof(struct node));
    pointer->symbol.name = strdup(name);
    pointer->symbol.addr = addr;
    pointer->hash = hash;
    pointer->next = symTab -> hash_table[index];
    symTab->hash_table[index] = pointer;
    return 1;
  }

  return 0;
}

2 个答案:

答案 0 :(得分:1)

这段代码是否会编译?

struct node pointer = calloc (1,sizeof(struct node));

我认为应该改为以下内容:

struct node * pointer = calloc (1,sizeof(struct node));

答案 1 :(得分:1)

  1. 发布@bialpio时,将变量声明更改为struct node * pointer。代码代表,编译代码或代码发布的代码不是真正的代码。

  2. 推荐更好的calloc()样式,这样会遇到这种编码问题。

    struct node *pointer = calloc(1, sizeof *pointer);
    
  3. 当然,并非所有警告都已启用。节省时间并启用它们。

相关问题