So the goal of this code snippet is to read in numbers from a file that represents the coefficients of a polynomial. The amount of numbers is not known before hand. There is one "polynomial" per line. Example of the file I am reading below.
Polynomails.txt
1 2 0 0 5
7.0 0 0 0 -2.25 1.13
Currently main only checks that a filename was given and that it can be opened, then calls ReadPoly, shown below. BUFFSIZE is a defined to be 256 with a define statement in this file.
void ReadPoly(FILE* InputFile){
polynomial poly;
double complex *coef;
char *p, *buffer;
unsigned int terms;
buffer = (char*) malloc(BUFFSIZE);
while(fgets(buffer,BUFFSIZE,InputFile)){
coef = (double complex*) malloc(BUFFSIZE*sizeof(double complex));
terms = 0;
p = strtok(buffer, " ");
while(NULL != p){
coef[terms] = atof(p);
terms++;
p = strtok(NULL, " ");
}
coef = (double complex*) realloc(coef,(terms*sizeof(double complex)));
printf("terms provided to init: %d\n",terms);
createPoly(&poly,terms);
poly.polyCoef = coef;
printf("terms in struct: %d\n",poly.nterms);
}
free(buffer);
}
And here is the createPoly function and the declaration of the poly struct.
typedef struct
{
unsigned int nterms; /* number of terms */
double complex *polyCoef; /* coefficients */
} polynomial;
void createPoly(polynomial *p, unsigned int nterms){
double complex terms[nterms];
p = (polynomial*) malloc(sizeof(polynomial));
p->nterms = nterms;
p->polyCoef = terms;
printf("In createPoly, nterms: %d\n",p->nterms);
}
Now from what I can tell all of the numbers are being read in properly, but the nterms value in the structure is not working as expected. Here is the output when I run this. Its worth mentioning that even with the same file input, the "terms in struct" value is not always the same.
terms provided to init: 6
In createPoly, nterms: 6
terms in struct: 1075624960
terms provided to init: 5
In createPoly, nterms: 5
terms in struct: 1075624960
My only though is that the polyCoef field of the struct is somehow writing over the nterms field but without fixed sizes(which are not an option) I'm unsure of how to proceed.