gpt4 book ai didi

c - fscanf 使我的 C 程序崩溃,不知道为什么

转载 作者:太空宇宙 更新时间:2023-11-04 01:00:25 27 4
gpt4 key购买 nike

编辑:问题已回答,我的第一个 for 循环中有错字。非常感谢大家收看。
我正在为 uni 开发一个 C 项目,但我遇到了一个我无法弄清楚的问题。在程序的一部分中,我必须将一些符号字符串读入结构(也称为“邮票”)中的二维字符数组。这是我的函数中的代码:

stamp_t * read_stamp_type1(FILE * fptr)
{
//variable declaration
int r = 0, c = 0;

//creating a struct stamp_t and mallocing memory
stamp_t *newstamp1;
newstamp1 = malloc(sizeof(stamp_t));

//reading in values for the rows and columns of the "stamp" to be read in
fscanf(fptr, "%d %d\n", &r, &c);

//storing these values
newstamp1->num_rows = r;
newstamp1->num_cols = c;

//creating memory for newstamp1's grid
newstamp1->grid = malloc(sizeof(char *) * (r));
for(int i=0; i < c; i++)
newstamp1->grid[i] = malloc(sizeof(char) * (c+1));

//string to temporarily store input
char rowvalues[c+1];

//Note: Everything works up until this point
//the below lines crash the program every time
for(int i = 0; i < r; i++)
{
fscanf(fptr, "%s", rowvalues);
for (int j=0; j < c; j++)
strcpy(newstamp1->grid[i], rowvalues);

}

free(rowvalues);

return(newstamp1);

}

出于某种原因,当我尝试从文本文件中 fscanf 字符串时,程序崩溃了(或者至少这就是我认为的原因......)。
作为引用,这里是结构声明:

// A structure for holding a stamp
typedef struct
{
// The size of the contents of this stamp.
int num_rows;
int num_cols;

// A 2D array of characters for a stamp.
char **grid;
} stamp_t;

这是程序的输入:

3 4
.#.@
#.#.
.#.@

任何建议将不胜感激,我似乎找不到代码的任何问题。我已经尝试手动为 rowvalues 数组中的每个值分配值,这工作正常(rowvalues[0] = 'c'; 工作正常)。我需要将 3 行符号读入 newstamp1.grid,这是一个二维数组。我运行了一个调试器,它说它试图写入不允许的内存(“访问冲突写入位置”)。我给我的教授发了电子邮件,但他上周没有上课,也没有回复电子邮件...
非常感谢。

最佳答案

对于初学者来说,这个循环中有一个拼写错误

newstamp1->grid = malloc(sizeof(char *) * (r));
for(int i=0; i < c; i++)
^^^^^^
newstamp1->grid[i] = malloc(sizeof(char) * (c+1));

必须有

for(int i=0; i < r; i++)
^^^^^^

这个循环

    for (int j=0; j < c; j++)
strcpy(newstamp1->grid[i], rowvalues);

没有意义。看来你的意思只是

strcpy(newstamp1->grid[i], rowvalues);

或者,如果文件中的每一行都包含 c 字符串,您可能必须分配一个 3D 字符数组(即二维字符串数组)。

还有这个声明

free(rowvalues);

错了。变量 rowvalues 具有自动存储持续时间。所以你不能为它调用函数 free

关于c - fscanf 使我的 C 程序崩溃,不知道为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42058510/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com