【发布时间】:2021-12-22 22:02:29
【问题描述】:
我正在尝试将单词插入哈希表,看起来它可以工作,但是当我尝试在节点内打印单词时(只是为了检查它是否仍然正确),我得到了一个虚假的值。当我的代码提示输入单词时,我说 'Hey',当它提示输入地点时,我说 '5'。打印出来的字符串(应该是节点内的单词)是 HH9[]A\A]A^A_f. 节点内的单词发生了什么,我在插入节点正确吗?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct node
{
char word[20];
struct node *next;
}
node;
int main (void)
{
node* table[10];
char wrd[10];
printf("Word to insert: ");
fgets(wrd, 10, stdin);
int place;
printf("Place to insert word: ");
scanf("%d", &place);
node *n = malloc(sizeof(node));
if(n == NULL)
{
return 1;
}
strcpy(n->word, wrd);
if(table[place] == NULL)
{
n = table[place];
n->next = NULL;
}
else
{
n->next = table[place];
n = table[place];
}
printf("Word inside node: %s \n" , n->word);
}
编辑
我更改了代码并尝试在更大范围内实现它,但我的 while 循环给了我一个段错误。这是我放入的函数:
FILE* dct = fopen ("/dictionaries/large", "r");
char *wrd = NULL;
while(fscanf(dct, "%s", wrd) != EOF)
{
int place = hash(wrd);
node *n = malloc(sizeof(node));
node *anchor = NULL;
node *end = NULL;
if(n == NULL)
{
return 1;
}
strcpy(n->word, wrd);
n->next = NULL;
if (!end) //Initial state
anchor = end = n;
else //Every following node.
end = end->next = n;
strcpy(n->word, wrd);
n->next = table[place];
table[place] = n;
counter++;
}
return false;
它必须从字典文件中读取并将单词加载到内存(或哈希表)中。
【问题讨论】:
-
您在将它设置为'next'的值后访问'n',此时为'NULL'。
-
数组
table未初始化。所有元素都将具有 indeterminate 值。 -
还要考虑
n = table[place]... 分配不应该是相反的吗? -
而且真的不需要
if(table[place] == NULL)检查。您只需要else案例(一旦您完成分配)。 -
如果你绝对需要一个表(这有点违背了链表的意义),你可以访问
table[5]->word。
标签: c linked-list nodes