C语言 具有冲突列表打印错误的哈希表



我有带有碰撞列表的哈希表(作为链表),当我运行它时程序崩溃。我认为问题出在 display() 函数中,该函数使用分配的键打印存储在一个列表中的所有值,也许是一些指针问题。我感谢你们的帮助。

struct node {
        long key;
        long long int data1,data2;
        struct node *next;
  };

  struct hash {
        struct node *head;
        int count;
  };
  struct hash *hashTable = NULL;
  struct node * createNode(long key, long long int data1,long long int data2) {
        struct node *newnode;
        newnode = (struct node *)malloc(sizeof(struct node));
        newnode->key = key;
        newnode->data1 = data1;
        newnode->data2 = data2;
        newnode->next = NULL;
        return newnode;
  }
void insertToHash(int key, long long int data1,long long int data2) {
        int hashIndex = key % eleCount;
        struct node *newnode =  createNode(key, data1, data2);
        if (!hashTable[hashIndex].head) {
                hashTable[hashIndex].head = newnode;
                hashTable[hashIndex].count = 1;
                return;
        }
        newnode->next = (hashTable[hashIndex].head);
        hashTable[hashIndex].head = newnode;
        hashTable[hashIndex].count++;
        return;
  }

void display(long key)  
{  
  struct node *cur_ptr;  
  long hashIndex = key % eleCount;
  cur_ptr=hashTable[hashIndex].head; 
  if(cur_ptr==NULL)  
  {  
     printf("nList is Empty");  
  }  
  else  
  {  
      printf("nElements in the List: ");  
      while(cur_ptr!=NULL)  
      {  
          printf("Key  : %lx , ", cur_ptr->key);
          printf("Pairs: (%llx,%llx)n", cur_ptr->data1,cur_ptr->data2);
          cur_ptr=cur_ptr->next;  
      }  
      printf("n");  
  }  
} 
   int main(void) {
        hashTable = (struct hash *)calloc(10, sizeof (struct hash));
        insertToHash(0xc767c053L,0x779d5a063fae2e7dLL,0x22499ae36fc6291fLL);
        insertToHash(0xc767c053L,0x2cf969e8a45cb021LL,0x198d9cca0f803198LL);
        insertToHash(0xf71a12d9L,0xde48739df8ab07fdLL,0x29902869a0887968LL);
        display(0xc767c053L);          
        return 0;
  }

你的哈希指数为负数。这:

void insertToHash(int key, long long int data1,long long int data2) {
        int hashIndex = key % eleCount;

应该是

void insertToHash(long key, long long int data1,long long int data2) {
        int hashIndex = key % eleCount;

另外,请始终检查来自malloc/calloc的返回。

从长远来看,如果您学习如何有效地使用 gdb 和 valgrind,您将节省时间。

最新更新