I have a file called pi.txt
which contains, as you probably imagine, the numbers of pi.
The format goes like this
Line 1: 3.
Line 2: 14159265358979323846264338327950288419716939937510
Line 3: 58209749445923078164062862089986280348253421170679
and it continues to
Line 20001: 56787961303311646283996346460422090106105779458151
There are 1020001 digits minus the 3
and the .
(of 3.14xxxxxx...)
I have to read this file to an array (not a 2D one. What I want to do later will become much harder if I use a 2D array as I imagine it). This is my code:
void fpi();
char **arraypi;
int main(int argc, char *argv[]) {
fpi();
int i;
while (i<=10){
printf("%d", arraypi[i++]);}
return 0;
}
void fpi(){
char pi[1020001];
arraypi = malloc(1020001 * sizeof(int));
FILE *file;
int i=0;
file = fopen("pi.txt", "r");
if (file == NULL){
printf("The file cannot be opened.\n");
exit(1);
}
while (fscanf(file, "%c", &pi)==1){
strcpy(arraypi[i++], pi);
}
fclose(file);
}
I get a segmentation fault and I can't figure out why. I'm sure it has to do with the pointers I'm using and fscanf
.