c - While 循环在条件出现之前停止

标签 c while-loop

我的代码有问题。我想加载一本适用于小字典的字典。但是当我尝试加载更大的版本时,我的 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*));

根据平台的不同,它可以是 48 。您需要分配更多内存。

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/

相关文章:

c# - 在 .NET/C# 中从数据库检索的子字符串值

CMake:定义自定义包含路径

将文件名连接到目录名

c - wait(null) and wait(&status) C语言与状态

c - 为什么此代码会导致无效指针?

java - Java 中的递归和 While 循环

c++ - 什么时候结束?

php - php while循环中的回显/打印问题

c++ - while循环和bool使程序结束

c - 与在命令行上使用文件名进行输入和输出的程序交互的最佳方式是什么?