Reputation: 103
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. 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).
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 !
Upvotes: 2
Views: 67
Reputation: 11921
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 = 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)
It should be
x = malloc(n * sizeof(*x)); /* it works for any type */
y = malloc(n * sizeof(*y));
Upvotes: 5
Reputation: 103
Nevermind, I found the solution.
It's just that I use malloc badly.
I wrote
x = malloc(n * sizeof(int));
When I should have written
x = malloc(n * sizeof(double));
Upvotes: 5