c - 扫描成结构

标签 c

我想最终将文件中的字符串插入到结构中的元素中,但无法正确插入。你能看出这里出了什么问题吗?

int main()
{
    FILE *fp;
    char file_name[10] = "map7.map";
    fp = fopen(file_name,"r");

    int a = 1;
    int *pnumberOfRows = &a;
    fscanf(fp,"%d",pnumberOfRows);

    typedef struct {
        bool visited;
        char *cityName;
    } map;

    map *ver = malloc(sizeof(map)*2*(*pnumberOfRows));

    fscanf(fp,"%s",ver[1].cityName);
    printf("%s",ver[1].cityName);

    return 0;
}

最佳答案

似乎您只是缺少为 char *cityName 字段分配空间,这使您 fscanf 到未分配的指针上。您可以提供固定字段,例如

typedef struct {
    bool visited;
    char cityName[81];
} map;

最大长度为 80 个字符(即 不包括 \0)或预先确定文件中城市名称的长度,然后使用

ver[0]->cityName = (char*)malloc(sizeof(char)*(stringLength+1));

请注意 sizeof(char) == 1,所以请随意将其保留,但请参阅答案 here了解更多信息。我把它留在这里是为了表达您想要实现的目标。

此外,不要忘记释放你在最后malloc的内存,并在完成后关闭文件描述符(即 fclose(fp);).

关于c - 扫描成结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28950773/

相关文章:

c - C语言中从socket读取数据

c - read() 没有读取完整的 http 响应

c - 如何用C语言编写加密函数

c - 阿杜诺 C : undefined reference to `readArms()'

c - 使用 shell 脚本在 c 中打印给定日期的日期。

c - 我找不到这个段错误

ios - setlocale() 在 iOS 模拟器中不起作用?

c - 为什么可以使用堆栈内的指针更改 const 值?

c - srand()——为什么只调用一次?

C信号量线程读取文件