Luigi Capogrosso Luigi Capogrosso - 11 months ago 53
C Question

Read (and convert) matrix on a file in C

I wrote this function in C:

void fill_matrix(double **m, int r, int c, char *file) {
int i, j;
FILE *temp_file = fopen(file, "r");
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++) {
fscanf(temp_file, "%lf", &m[i][j]);
}
}
fclose(temp_file);
}


Matrix is defined and allocated in this way:

double **m;
m = (double **) malloc(r * sizeof(double *));
for(i = 0; i < r; i++)
m[i] = (double *) malloc(c * sizeof(double));


r and c is the number of rows and columns.

Params are:

fill_matrix(m, r, c, filename);


In the testin.txt file I have this matrix:

1 2 3 4
5 6 7 8
9 1 2 3


But my out is:

1.00 0.00 0.00 0.00
5.00 6.00 0.00 0.00
9.00 1.00 2.00 3.00


Can you please let me know how to solve this? Thanks for your time.

Answer Source

I have no idea why are you getting your results, but this code works in VS2017CE:

#include "stdafx.h"
#include "stdlib.h"
#include "stdio.h"

void fill_matrix(double **m, int r, int c, char *file);

int main()
{
    double **m;
    int rows = 3;
    int cols = 4;
    m = (double**)malloc(sizeof(double*)*rows);
    for (int i = 0; i < rows; ++i)
    {
        m[i] = (double*)malloc(sizeof(double)*cols);
    }

    fill_matrix(m, rows, cols, "testin.txt");

    FILE *outfile = fopen("testout.txt", "w");
    for (int i = 0; i < rows; ++i)
    {
        for (int j = 0; j < cols; ++j)
        {
            fprintf(outfile, "%lf ", m[i][j]);
        }
        fprintf(outfile, "\r\n");
    }
    fclose(outfile);
    return 0;
}

void fill_matrix(double** m, int r, int c, char *file) {
    int i, j;
    FILE *temp_file = fopen(file, "r");
    for (i = 0; i < r; i++) {
        for (j = 0; j < c; j++) {
            fscanf(temp_file, "%lf", &m[i][j]);
        }
    }
    fclose(temp_file);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download