我的代码有问题。我想加载一本适用于小字典的字典。但是当我尝试加载更大的版本时,我的 while 循环停在第 701 个单词“acclimatization”处,然后程序继续。我在论坛上搜索了很多并尝试了很多东西,但我就是找不到造成这种情况的原因。有谁知道这是如何发生的吗?
字典.c
bool load(const char* dictionary)
{
// reserve space for word
char* word = malloc(sizeof(char*));
// open file
FILE* dict = fopen(dictionary, "r");
if (dict == NULL)
{
fclose(dict);
fprintf(dict, "Could not load %s.\n", dictionary);
return 1;
}
root = (struct node *) malloc(sizeof(struct node));
root->is_word = false;
//Loops over word aslong the EOF is not reached
while (fgets(word,LENGTH,dict) != NULL)
{
printf("word = %s\n", word);
int word_length = strlen(word) -1;
node* current = root;
word_count++;
//Loops over letters
for (int i = 0; i < word_length; i++)
{
int index;
node *next_node;
// checks if letter isnt a apostrophe
if(word[i] == 39)
{
index = MAX_CHARS - 1;
}
// gets nummeric value of letter
else
{
index = tolower(word[i]) - 'a';
}
next_node = current->children[index];
// creates new node if letter didnt exists before
if(next_node == NULL)
{
next_node = malloc(sizeof(node));
current->children[index] = next_node;
current->is_word = false;
printf("new letter: %c\n", word[i]);
}
else
{
printf("letter: %c\n", word[i]);
}
// checks for end of the word
if(i == word_length - 1)
{
next_node->is_word = true;
}
current = next_node;
}
}
return true;
}
节点定义为:
// node
typedef struct node
{
bool is_word;
struct node* children[27];
}
node;
最佳答案
char* word = malloc(sizeof(char*));
根据平台的不同,它可以是 4
或 8
。您需要分配更多内存。
char* word;
word = malloc(LENGTH); // LENGTH as you use it here while (fgets(word,LENGTH,dict) != NULL)
if(word!=NULL){ // and checking if malloc is successful
// your code
free(word); // freeing allocated memory
return true;
}
else { // executed only if malloc fails
//handle error
}
您可以提供任何所需的尺寸。
注意 - 使用函数 free()
,每次分配内存时都需要释放。
关于c - While 循环在条件出现之前停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32843949/