gpt4 book ai didi

使用 fscanf 从文件中的数据生成数组时出现 C 段错误

转载 作者:行者123 更新时间:2023-12-02 06:13:48 24 4
gpt4 key购买 nike

我已经尝试找到我的问题的解决方案,但我没有找到,所以我将其发布在这里。

我想读取一个文件,然后根据我得到的数据创建两个一维数组。文件是这样的:

  • 第一行:要收集的数据数量
  • 其他行:我要获取的数据

这是我的文件:

7
1. 4.1
2. 8.2
5 19.5
12 50
20 78
30 50.05
50 5

7 是我想要获取的行数(我想要从 1 到 50 的所有行)。

我编写的代码返回了一个段错误,但我不明白为什么。
这是我写的:

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

int main(void)
{
/* DECLARATION OF CONSTANTS AND VARIABLES */
FILE* fichier = NULL;
double* x = NULL;
double* y = NULL;
int k,n = 0;

/* OPENING FILE */
fichier = fopen("donnees1.txt", "r+");

if (fichier != NULL)
{
fscanf(fichier, "%d", &n);

/* creating dynamic array of x and y */
x = malloc(n * sizeof(int));
y = malloc(n * sizeof(int));

if (x == NULL)
{
printf("failed to allocate.\n");
exit(0);
}

for(k = 0; k < n; k++)
{
fscanf(fichier, "%lf %lf", &x[k], &y[k]);
printf("%lf %lf\n", x[k],y[k]);
}
/* Closing file */
fclose(fichier);
}
else
{
printf("Cannot open the file.\n");
}

/* Freeing memory */
free(x);
free(y);
return 0;
}

这就是程序返回给我的内容:

1.000000 4.100000
2.000000 8.200000
5.000000 19.500000
12.000000 50.000000
20.000000 78.000000
30.000000 50.050000
50.000000 5.000000
Segmentation fault

感谢您的帮助和关注!

最佳答案

我写的代码返回了一个段错误?段错误导致的语句如下,因为 xy 的内存分配不正确.

x = malloc(n * sizeof(int));
y = malloc(n * sizeof(int));

(因为在大多数机器上 sizeof(double) 大于 sizeof(int) 所以一段时间后没有足够的空间容纳数组元素)

应该是

x = malloc(n * sizeof(*x)); /* it works for any type */
y = malloc(n * sizeof(*y));

关于使用 fscanf 从文件中的数据生成数组时出现 C 段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49274826/

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