1

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?

2 Answers 2

1

You're using the %d format specifier for a double. You should try %f.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

6 Comments

It is some test code, but these are important things to consider none the less. The caller will advance through the location in memory the same way I am right now in this method. That should work, correct?
Not with retval advanced the way it is being done currently. What you want to return to caller is the head of the array not the tail.
I just added something that should fix that, is there a more clever way or will this be sufficient?
You could towards the top end of code (1) double* array_head = retval; after the alloc, and at bottom (2) return array_head; You will not need the for loop
And I am also mildly curious if my answer actually helped fix your problem :)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.