0

我有带有冲突列表的哈希表(作为链表),当我运行它时程序崩溃。我认为问题出在 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;
  }
4

1 回答 1

1

你的 hashIndex 是负数。这个:

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,您将节省时间。

于 2013-11-02T15:06:48.310 回答