我正在学习C语言并调试代码,以便对选定的文本文件进行拼写判断.我这里的最后一个障碍是我的hashmap的加载函数.它成功地从词典文件中读取给定的单词,将其存储,并将其分配给临时node *
,但当我try 创建 struct node *table[] = tmp
时,问题出现了;
有什么 idea 吗?此外,我的散列函数工作正常,不是问题所在.谢谢大家.
Edit:看起来好像table->next
没有更新到指向单链表中下一项的指针.当我try 做new_word->next = table[index];
它不改变地址和停留作为0x00
.
bool load(const char *dictionary)
{
// open up file to read dictionary to
FILE *dict = fopen(dictionary, "r");
if (dict == NULL)
{
printf("Error opening dictionary file.\n");
return 1;
}
// create variable to store the current word in
char *current_word = malloc(LENGTH * (sizeof(char)));
if (current_word == NULL)
{
printf("Error in allocating memory.\n");
return 1;
}
// initialize index for finding hash index, and count, to store word count
int index;
int count = 0;
while (fgets(current_word, LENGTH, dict) != NULL)
{
//open up a node to store the current new word in, also store current word
node *new_word = malloc(sizeof(node));
if (new_word == NULL)
{
printf("Error allocating memory.\n");
return 1;
}
// copy word to new world variable, store next pointer in variable as well,
// set as new head of table listy
strcpy(new_word->word, current_word);
index = hash(new_word->word);
new_word->next = table[index];
table[index] = new_word;
free(new_word);
count++;
}