Reputation: 427
So I'm reading values from a file delimited by a comma and assigning it to a 1D array of doubles. Here is the method I'm using to accomplish this:
double* readFile(char *fileName)
{
FILE *fp = fopen(fileName, "r");
char *token;
int i = 0;
int j = 0;
double *retval = (double *)malloc(5000 * sizeof(double));
if(fp != NULL)
{
char line[10];
while(fgets(line, sizeof line, fp) != NULL)
{
//printf("Parsed line: %s\n", line);
token = strtok(line, ",");
while(token != NULL)
{
printf("token: %s\n", token);
*retval = atof(token);
printf("value: %d\n",*retval);
retval++;
token=strtok(NULL,",");
}
}
fclose(fp);
} else {
perror(fileName);
}
for(j = 0; j < i; j++)
{
retval--;
}
return retval;
}
The problem I'm getting is that after I assign the atof() of the tokenized value, which is correct, the value that is saved in the pointer is absolutely incorrect. For instance, I have a textfile which is just all zeros, and whats being saved in the array is crazy values like -1587604999 in every single position.
Anyone see the problem?
Upvotes: 1
Views: 42
Reputation: 4561
retval
has advanced and is now pointing to the next usable location.
You want to save the original malloc
value and return that.
There might be other issues too, for example how does the caller know where the values end? Also, what if you get more than 5000 values? Also, free memory on error. But I assume this is merely your test code and you will eventually address these things.
Upvotes: 1
Reputation: 2476
You're using the %d
format specifier for a double. You should try %f
.
Upvotes: 1