在c中插入链接列表时值错误



我正试图将单词插入哈希表中,它看起来很有效,但当我试图在节点内打印单词时(只是为了检查它是否仍然正确(,我得到了一个伪值。当我的代码提示输入单词时,我说"嘿">,当它提示输入位置时,我会说'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循环给了我一个segfault。这就是我把它放进去的功能:

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;

它必须从字典文件中读取并将单词加载到内存(或哈希表(中。

链表是链表,因为它没有固定的大小。因此CCD_ 1阵列是多余的。你需要的是记住你的链接列表的锚,而不是更多。

一个小例子:

Node *anchor = NULL;
Node *end = NULL;
Node *node = malloc(sizeof(Node));
node->next = NULL;
if (!end)    //Initial state
anchor = end = node;
else        //Every following node.
end = end->next = node;

此时,您仍然可以访问刚刚填写的node。不要忘记稍后迭代您的列表,然后free这些分配。

此代码没有任何意义:

if(table[place] == NULL)
{
n = table[place]; // since we know table[place] is null, that sets n to null!
n->next = NULL;   // We just set n to NULL, we can't access n->next!
}
else
{
n->next = table[place]; // This sets n to a garbage value since table[place] was never assigned a value

n = table[place]; // This leaks the value we malloc'ed. We were supposed to link it to the list!
}

最新更新