2017-05-27 182 views
0

因此,我正在将文件中的所有单词读入链表中。我有一个单独的链表,每个字母的单个字母。尝试将新节点插入链表时程序崩溃。为什么?

这里的结构:

struct WORD { 
    char* word; 
    int noOfUse; 
    struct WORD* next; 
}; 

和数组:

struct WORD* dictionary[26]; 

,循环读取所有的话:

do { 
    fscanf(fp, "%s", buffer); 
    printf("%s\n", buffer); 
    dictionary[buffer[0]-'a'] = insertWord(buffer, dictionary[buffer[0]-'a']); 
} while (!feof(fp)); 

而且功能:

struct WORD* insertWord (char buffer[30], struct WORD* node){ 
if (node == NULL){ 
    node = (struct WORD*) malloc (sizeof(struct WORD)); 
    node->word = (char*) malloc (strlen(buffer)+1); 
    strcpy(node->word, buffer); 
    node->next = NULL; 
} 
else { 
    node->next = insertWord(buffer, node->next); 
} 
return node; 
} 

我看不出我在做什么错她,但程序崩溃,只要我运行它。我是否想要到达我不想接触的地方?

+0

“字典”是否已初始化?元素是否都是“NULL”?而如果输入不是小写字母呢? –

+0

顺便说一句,如果'node'不是'NULL',那么你有无限递归。 –

+0

在这种情况下它们都是小写字母。字典是否需要初始化?无论如何,我希望它的所有元素在开始时都是空的。我宁愿在函数内初始化它们。 –

回答

2

首先struct WORD* dictionary[26];这可以用垃圾来初始化,你应该设置26个指针为NULL,也

else { 
    node->next = insertWord(buffer, node); 
} 

这一点,如果节点!= NULL,然后你再一次把它传递给insertWord功能此执行,那么再次节点!= NULL,你再次启动这个函数......,它是无限递归。

还记得大写字母。

+0

谢谢!有效。愚蠢的我,我应该发送node-> next作为参数。 –