C 数组指针始终指向NULL

C 数组指针始终指向NULL,c,C,我正在尝试在节点数组中创建一个链表。当我尝试将arrTab->h_table[index]的指针更新到newNode的地址时,该地址指向newNodes地址。但是,当我尝试添加到数组中存在的列表时,指针总是指向NULL,而不是内存中的上一个值。基本上,链表的arrTab->h_table[index]头不会更新为newNode的地址 typedef struct node { struct node* next; int hash; s_type

我正在尝试在节点数组中创建一个链表。当我尝试将arrTab->h_table[index]的指针更新到newNode的地址时,该地址指向newNodes地址。但是,当我尝试添加到数组中存在的列表时,指针总是指向NULL,而不是内存中的上一个值。基本上,链表的arrTab->h_table[index]头不会更新为newNode的地址

typedef struct node {
  struct node* next;     
  int          hash;     
  s_type     symbol;
} node_t;


struct array {
  int      cap;    
  int      size;       
  n_type** h_table;
};



int add_to_array (array* arrTab, const char* name, int address) {
  if(s_search(arrTab, name, NULL, NULL) == NULL){
    s_type *symbol = (s_type*) calloc(1, sizeof(s_type));
    symbol->name = strdup(name);
    symbol->addr = addr;
    n_type  *newNode = (n_type*) calloc(1, sizeof(n_type));
    newNode->next = NULL;
    newNode->hash = nameHash(name);
    newNode->symbol = *symbol;
    int index = newNode->hash % arrTab->cap;
    if(arrTab->h_table[index] == NULL){
      arrTab->h_table[index] = newNode;
    } else {
      newNode->next = arrTab->h_table[index];
      arrTab->h_table[index] = newNode;
    }
    //
    arrTab->size++;
    return 1;
  }
  return 0;
}

struct node* s_search (array* arrTab, const char* name, int* hash, int* index) {
  int hashVal = nameHash(name);
  hash = &hashVal;
  int indexVal = *hash % arrTab->cap;
  index = &indexVal;
  s_type *symCopy = arrTab;
  while (symCopy->h_table[*index] != NULL){
    if(*hash == symCopy->h_table[*index]->hash){
      return symCopy->h_table[*index];
    }
    symCopy->h_table[*index] = symCopy->h_table[*index]->next;
  }
  return NULL;
}
我不能确定为什么指针总是指向NULL;没有足够的代码。考虑发布./P> 然而,发布的代码没有什么问题需要解决

首先,它像没有明天一样泄漏内存:

symbol_t *symbol = (symbol_t*) calloc(1, sizeof(symbol_t));
分配一些内存,然后

newNode->symbol = *symbol;
将该内存的内容复制到新位置。分配的内存仍然存在,并在函数返回后继续存在-但无法访问它。我强烈建议不要分配符号,直接使用newNode->symbol:

符号搜索的散列和索引参数似乎计划作为输出参数。在这种情况下,请注意hash=&hashVal;和索引=&indexVal;打电话的人看不见。您可能是指*hash=hashVal和*index=indexVal

最大的问题是sym_table_t*symCopy=symTab

symTab是一个指针。它指向一个实际的符号表,一大块内存。赋值后,symCopy指向同一块内存。也就是说

symCopy->hash_table[*index] = symCopy->hash_table[*index]->next;
修改那段记忆。搜索完成后,哈希表[索引]与搜索前不同。这可能是你问题的根源。无论如何,请考虑

node_t * cursor = symTab->hash_table[*index];
并改为使用此光标

作为旁注,搜索条件*hash==symCopy->hash_table[*index]->hash很奇怪。给定链表中的每个节点都有相同的哈希检查,检查如何添加它们。第一个节点将产生匹配,即使名称不同。

主持人注意:请不要破坏您的帖子。一旦你发布了一个问题,它们就属于网站及其用户。即使它对你不再有用,它也可能对将来的某个人有所帮助。回答者也会努力写下他们的答案,如果你从帖子中删除了内容,这将不再有用。另外,请注意,通过在Stack Exchange网络上发布,您已经授予SE在CC by-SA 3.0许可证下分发该内容的不可撤销的权利。根据SE政策,任何故意破坏行为都将恢复原状。
node_t * cursor = symTab->hash_table[*index];