I am trying to scan in a list of data from a text file, and that data is supposed to be put into an array of type double, and this must be done in a function outside of main. Therefore the pointer needs to be to the array in main, from the function actually scanning the data into the array.
The problem comes when I attempt to make the function return the array through a pointer like (assuming the prototype is already existing):
#include <stdio.h>
#include <stdlib.h>
#define SIZE 12
int
main(void)
{
double data[SIZE];
int i;
readData(data, SIZE);
}
void
readData(double data[], int SIZE)
{
FILE* fp;
fp = fopen("data.txt", "r");
int i;
for (i = 0; i < SIZE; i++)
{
fscanf(read, "%lf", &data[i]);
if(data[i] < 0)
printf("Negative data at %d\n", i);
}
printf("The array is: ");
for (i = 0; i < SIZE; i++)
{
printf("%f ", data[i]);
}
fclose(fp);
return;
}
This simply gives me a run time error and crashes, with no compile error at all. I'm guessing it's due to the fact that the fscanf is attempting to write to &*data[CONST]
but I have no idea how else to get it to write to the pointer, and not just a local variable.
Is there some trick to getting file input into a function pointer?