【问题标题】:fgets and sscanf with a struct causing unexpected resultsfgets 和 sscanf 的结构导致意外结果
【发布时间】:2013-04-26 00:38:32
【问题描述】:

我正在编写一个程序,我需要从平面文件中获取一行。然后我 sscanf 将数据放入结构中。这给了我非常意想不到的结果。首先,这是一个类似于我想做的工作示例。我有一个文件 department.in,如下所示:

0 something
1 else
2 more

这是一个示例程序,它运行并给出了我期望的结果:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{

    FILE *in;
    in = fopen("department.in", "r");

    char * buffer = malloc(256 * sizeof(char));
    while((fgets(buffer, 256, in)) != NULL){

            int index;
            char* name;
            sscanf(buffer, "%d %s", &index, name);

            printf("\n\nIndex: %d, Name: %s.\n\n", index, name);
    }

    free(buffer);

    return 0;
}

正如预期的那样,结果是:

Index: 0, Name: something.

Index: 1, Name: else.

Index: 2, Name: more.

但是,当我添加一个结构时,它编译得很好:

#include <stdio.h>
#include <stdlib.h>

typedef struct{
    int index;
    char* name;
}test;

int main(void)
{

    FILE *in;
    in = fopen("department.in", "r");

    char * buffer = malloc(256 * sizeof(char));
    while((fgets(buffer, 256, in)) != NULL){

            test *mytest = malloc(sizeof(test));

            sscanf(buffer, "%d %s", &mytest->index, mytest->name);

            printf("\n\nIndex: %d, Name: %s.\n\n", mytest->index, mytest->name);
            free(mytest);
    }
    free(buffer);
    return 0;
}

结果不是我所期望的:

Index: 0, Name: (null).

Index: 1, Name: (null).

Index: 2, Name: (null).

显然,我的 char 做错了什么,但我终其一生都无法弄清楚是什么。当我改变某些东西时,它甚至会出现故障。任何帮助将不胜感激!

附:这不是家庭作业。我刚刚为我的实际代码制作了一个更加简化的示例,以便在此处阅读和编译以及学习我需要的这个概念。再次感谢!

【问题讨论】:

    标签: c struct fgets scanf


    【解决方案1】:

    将存储分配给mytest-&gt;name。输出告诉你指针为 NULL。

    mytest->name = malloc(256); /* sizeof(char) is always 1, by definition */
    

    或者您可以将指针替换为数组。

    typedef struct{
        int index;
        char name[256];
    }test;
    

    顺便说一句,做一个简化的例子做得很好。

    【讨论】:

    • 第二部分确实有效!当然......我知道我错过了一些东西。您将如何正确地将存储分配给 mytest->name?
    • 我不敢相信我没有看到!谢谢你:)
    猜你喜欢
    • 2013-02-19
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 2018-07-04
    • 2014-09-04
    • 2013-09-14
    相关资源
    最近更新 更多