So, I am trying to read a matrix from a file and store it into an array.
The matrix files are as follows:
2 3
1 5 8
6 3 9
With the first two digits on the first line representing Rows x Columns.
I seem to be getting an issue whenever I try to store something into my array, as I am able to simply reprint everything to the screen, but I when I try to reprint, I get different values than intended.
My code is as follows:
double *read_matrix(char *filename){
FILE *file=fopen(filename, "r");
if(!file){
fprintf(stderr, "An error has occurred. Wrong file name?\n");
exit(errno);
}
double *data=malloc(4096*sizeof *data);
char *buff=malloc(256*sizeof *buff);
char *curr;
char *save;
while(fgets(buff,sizeof(buff),file)){
curr=strtok_r(buff," ",&save);
int i=0;
while(curr!=NULL){
if(curr==NULL){
perror("curr is null");
}
data[i]=strtod(curr,NULL);
curr=strtok_r(NULL," ",&save);
i++;
}
}
free(buff);
return data;
}
Whenever I run this and try to print the first two values of my array I get the following for my rows and columns:
A: 0.000000 | -1.000000
I am having troubles understanding what I have done wrong, if it's not one problem it's another!
I'm not sure if it helps, but below you can find the method that calls read_matrix():
void executemm(char *file1, char *file2)
{
double *matrixA = read_matrix("matrix1");
printf("A: %f | %f\n", matrixA[0], matrixA[1]);
}
All it does is specify the file to read from, and then display the first two elements of the returned array (which should be the dimensions).
EDIT: Update to code block, and updated actual output
EDIT 2: Again, updating code block, and updated actual output