c - 插入函数哈希表C

标签 c insert hashtable

我在为哈希表实现插入函数时遇到问题。

所以我实现了一些测试调用,我只是单独调用该函数。对于实际使用,我在 while 循环内调用该函数。出于测试目的,我只运行循环 4 次。

我在下面发布了一些输出。该表看起来很奇怪的原因是我的哈希函数。它对单词进行哈希处理,使得 A = 1、B = 2、C = 3 等等。字母在单词中的位置无关紧要,因为我将考虑单词的排列。此外,该问题中字母的大小写也无关紧要,因此 a 的值 = A 的值 = 1。

对于字符串,abc = 1 + 2 + 3 = 6,bc = 2 + 3 = 5,等等

总体来说,哈希函数还是不错的。问题出在插入函数上。

我的本​​地词典的前 4 个单词是 A、A's、AA's、AB's。

我的预期输出应该是(当我运行测试调用时得到相同的输出):

0: 
1: [W: A, Len:1] 
2: 
3: 
...
18: 
19: 
20: [W: A's, Len:3] 
21: [W: AA's, Len:4] 
22: [W: AB's, Len:4]

但是当我在循环内调用该函数时,列表中最后的内容将覆盖其他条目。如果我运行循环 100 次,那么最后一个条目仍然会替换前面的条目(注意单词的长度没有改变,但只有单词被替换):

0: 
1: [W: AB's, L:1] 
2: 
3: 
...
18: 
19: 
20: [W: AB's, Len:3] 
21: [W: AB's, Len:4] 
22: [W: AB's, Len:4] 

下面是我的代码:

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

int hash(char *word)
{
   int h = 0;

   while(*word != '\0')
   {
      if(*word >='A' && *word < 'A'+26) {
         h=h+(*word -'A' + 1);
      }
      else if(*word >='a' && *word < 'a'+26) {
         h=h+(*word -'a' + 1);
      }
      //else { // special characters
      // return -1;  
      //}

      word++;
   }

   return h;
}

typedef struct Entry {
   char *word;
   int len;
   struct Entry *next;
} Entry;

#define TABLE_SIZE 1000 // random numbers for testing

Entry *table[TABLE_SIZE] = { NULL }; // an array of elements

void init() {
   int i;

   for (i = 0; i < TABLE_SIZE; i++) {
      // initialize values
      struct Entry *en = (struct Entry *)malloc(sizeof(struct Entry));

      en->word = "";
      en->len = 0;
      en->next = table[i];
      table[i] = en;
   }
}

//Insert element
void insertElement(char *word, int len) {
   int h = hash(word);
   int i;

   // because all words are different so there is no need to check for duplicates
   struct Entry *en = (struct Entry *)malloc(sizeof(struct Entry));

   en->word = word;
   en->len = len;
   en->next = table[h];
   table[h] = en;
}

void cleanTable()
{
   struct Entry *p, *q;
   int i;

   for( i=0; i<TABLE_SIZE; ++i )
   {
      for( p=table[i]; p!=NULL; p=q )
      {
         q = p->next;
         free( p );
      }
   }  // for each entry
}

int main() {
   init(); // create hash table

   // test calls produce correct output
   //insertElement("A", (int)strlen("A"));
   //insertElement("A's", (int)strlen("A's"));
   //insertElement("AA's", (int)strlen("AA's"));
   //insertElement("AB's", (int)strlen("AB's"));

   int i;
   i = 0;

   FILE* dict = fopen("/usr/share/dict/words", "r"); //open the dictionary for read-only access 
   if(dict == NULL) {   
      return;                    
   }

   // Read each line of the file, and insert the word in hash table
   char word[128];      
   while(i < 4 && fgets(word, sizeof(word), dict) != NULL) {
      size_t len = strlen(word); 
      if (len > 0 &&  word[len - 1] == '\n') {
         word[len - 1] = '\0'; // trim the \n
      }

      insertElement(word, (int)strlen(word));

      i++;
   }

   for ( i=0; i < 50; i++)
   {
      printf("%d: ", i);

      struct Entry *enTemp = table[i];

      while (enTemp->next != NULL)
      {
         printf("[W: %s, Len:%d] ", enTemp->word, enTemp->len);
         enTemp = enTemp->next;
      }

      printf("\n");
   }

   cleanTable();

   return 0;
}

最佳答案

尝试在这部分代码的每个循环中重新分配内存:

char* word = malloc(sizeof(char)*128);      
while(i < 4 && fgets(word, sizeof(word), dict) != NULL) {
    size_t len = strlen(word); 
    if (len > 0 &&  word[len - 1] == '\n') {
        word[len - 1] = '\0'; // trim the \n
    }
    insertElement(word, (int)strlen(word));
    word = malloc(sizeof(char)*128);
    i++;
}

您忘记为每个字符串重新分配内存,这导致所有指针都指向同一点

注意:未经测试

关于c - 插入函数哈希表C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372693/

相关文章:

objective-c - 哈希表中的 ARC 弱引用

MYSQL INSERT IF SUM > CONSTANT

powershell - 将两个哈希表连接成一个

c 初学者, vector

c - 如何将随机生成的单词应用到条件中? - C

c - 防止 GCC 改变结构的大小(.BMP 文件头)

c - 如何查看结构体指针中的结构体是否包含元素

matlab - 用Matlab将矩阵插入另一个矩阵

sql - 如何使用具有多个结果的子查询将值插入表中?

c# - 静态哈希表应该有多少容量才能最大程度地减少冲突?