[英]C segfault while using fscanf to make array from datas in a file
我已经尝试找到解决问题的方法,但我没有找到,所以我在这里发布。
我想读取一个文件然后从我得到的数据创建两个1D数组 。 该文件是这样的:
这是我的档案:
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
感谢您的帮助和关注!
没关系,我找到了解决方案。
只是我使用malloc非常糟糕。 我写
x = malloc(n * sizeof(int));
什么时候我应该写
x = malloc(n * sizeof(double));
我写的代码给我一个分段错误? 由于x
和y
内存分配不正确,因此分段故障导致语句如下所示。
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.