【问题标题】:C - same data in dynamic structC - 动态结构中的相同数据
【发布时间】:2013-05-23 23:50:28
【问题描述】:

这是我的代码:

 #include <stdio.h>
    #include <stdlib.h>
    #define STR_LEN 255
    #define TRUE 1

    typedef struct
    {
        int id;
        char text[STR_LEN];
        char answer[4][STR_LEN];
        int correct_answer;
        char date[STR_LEN];
        char author[STR_LEN];
        int difficulty;
    } Question;

    typedef struct
    {
        Question* new_question;
        struct List* next;
    } List;

    List* listFromFile(List* root, FILE* file)
    {
        List* current_item;
        Question* q;
        root = (List* ) malloc(sizeof(List));
        q = (Question* ) malloc(sizeof(Question));
        if(!fread(q, sizeof(Question), 1, file))
        {
            printf("No data in the file");
            exit(1);
        }
        root->new_question = q;
        root->next = NULL;

        do
        {

            current_item = (List* ) malloc(sizeof(List));
            current_item->next = NULL;
            if (!fread(q, sizeof(Question), 1 , file))
            {
                free(current_item);
                break;
            }
            current_item->new_question = q;
            current_item->next = root;
            root = current_item;

        }
        while(TRUE);

        free(q);
        return root;
}
int main()
{
    List* root = NULL;
    List* item;
    int count_id = 1;
    int choice;
    system("CLS");
    FILE* file;
    if ((file = fopen ("questions.bin", "rb")) != NULL)
    {
        root = listFromFile(root, file);
        count_id = root->new_question->id;
        printf("Questions loaded!\n\n\n\n");
        if ((fclose(file)) != 0)
            printf("ERROR - cannot close file!\n");
    }
    else printf("No questions found! Please add questions.\n\n\n");

问题是当我尝试打印列表时,每个列表元素中都有相同的信息,我不知道为什么。幸运的是,列表元素的编号与文件中的编号相同,但是我将信息放入其中的方式有​​问题。有人知道这是为什么吗?

【问题讨论】:

    标签: c list dynamic struct


    【解决方案1】:

    您正在使用q 指向的相同分配的内存块将问题分配给节点,但每次阅读新问题时也会覆盖它。您需要malloc 为每个问题分配唯一的缓冲区。

    do {
    
       current_item = (List* ) malloc(sizeof(List));
       q = (Question* ) malloc(sizeof(Question));
       /* ... */
    } while (1);
    

    【讨论】:

    • 还建议检查所有 malloc 输出以捕获 NULL 返回
    【解决方案2】:

    添加一个点。

        do
        {
    
            current_item = (List* ) malloc(sizeof(List));
            if (!current_item)
            {
                printf("malloc error\n");
                break;
            }
            ...
        }
        while(TRUE);
    
        //free(q); //you couldn't free the q pointer here or else may cause segfault
        return root;
    

    因为你的代码在 main 函数中。

        count_id = root->new_question->id;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      • 2013-08-11
      • 2020-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      相关资源
      最近更新 更多