1

这是我的代码:

 #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");

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

4

2 回答 2

1

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

do {

   current_item = (List* ) malloc(sizeof(List));
   q = (Question* ) malloc(sizeof(Question));
   /* ... */
} while (1);
于 2013-05-23T23:53:23.597 回答
0

添加一个点。

    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;
于 2013-05-24T02:04:47.887 回答