Here is the code for the whole routine
Code:
float *f_retrieve_vector(char filename[], int n)
// in most cases n= 1000;
{
FILE* fp;
int k= 0;
float *f;
float fprime= 0;
char * pch;
char buf[1024];
if ((fp= fopen(filename, "rt"))==NULL)
{
printf("could not open %s in f_retrieve_vector() in structures.c\nexiting to system\n", filename);
exit(-1);
}
f= calloc(n, sizeof(float));
if (f== NULL)
{
printf("could not allocate memory for vector f in f_retrieve_vector()\nexiting..\n");
exit(-1);
}
k= 0;
// read a line into the buffer
while (fgets(buf, sizeof(buf), fp)!=NULL)
{
pch = strtok(buf, ",");
while (pch != NULL)
{
sscanf(pch, "%g", &fprime);
f[k]= fprime;
pch= strtok(NULL, ",");
k++;
}
}
if (k!=n)
printf("fewer than %d (read %d) entries read in from file %s in f_retrieve_vector()\nremaining values will be ZEROED\n", n, k, filename);
fclose(fp);
return f;
}
f is a pointer to a chunk of memory allocated by calloc of type float.
The while loop scans over the input buffer, which has n items in a comma delimited list. k is just incremented everytime an item is read from the list, and k <= n.
The problem though doesn't exist with the assignment of f[k]= frpime, it exists with the sscanf, because I get exactly the same problem if I remove the f[k]= fprime line.