[英]C segfault while using fscanf to make array from datas in a file
I already tried to find a solution to my problem but I didn't find it so I post it here. 我已经尝试找到解决问题的方法,但我没有找到,所以我在这里发布。
I want to read a file and then create two 1D arrays from the data I got . 我想读取一个文件然后从我得到的数据创建两个1D数组 。 the file is like that:
该文件是这样的:
Here is my file : 这是我的档案:
7
1. 4.1
2. 8.2
5 19.5
12 50
20 78
30 50.05
50 5
7 is the number of line I want to get (I want all the lines from 1. to 50). 7是我想要获得的行数(我想要从1到50的所有行)。
The code I wrote return me a segmentation fault but I don't understand why. 我写的代码给我一个分段错误,但我不明白为什么。
Here is what I wrote : 这是我写的:
#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;
}
This is what the program is returning me : 这就是程序给我的回报:
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
Thank you for your help and for your attention ! 感谢您的帮助和关注!
Nevermind, I found the solution. 没关系,我找到了解决方案。
It's just that I use malloc badly. 只是我使用malloc非常糟糕。 I wrote
我写
x = malloc(n * sizeof(int));
When I should have written 什么时候我应该写
x = malloc(n * sizeof(double));
The code I wrote return me a segmentation fault ? 我写的代码给我一个分段错误? segmentation fault causing statement is below as memory allocation for
x
and y
is not correct. 由于
x
和y
内存分配不正确,因此分段故障导致语句如下所示。
x = malloc(n * sizeof(int));
y = malloc(n * sizeof(int));
(because on most machines sizeof(double)
is bigger than sizeof(int)
so there's not enough room for the array elements after a while) (因为在大多数机器上
sizeof(double)
大于sizeof(int)
所以一段时间后数组元素没有足够的空间)
It should be 它应该是
x = malloc(n * sizeof(*x)); /* it works for any type */
y = malloc(n * sizeof(*y));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.