cvisual-studio-codepointersmatrix

C code reading only part of a matrix correctly


While trying to read the following matrix from a .dad file

 1  3 −3  1
−1  3  2  0
 2  4  0  7

the program bizarrely only reads the first two values:

PS C:\Users\...\P1> gcc -o main_gauss main_gauss.c linalg.c  
PS C:\Users\...\P1> ./main_gauss.exe

Matrix A:
1.000000 3.000000 0.000000 0.000000 
0.000000 0.000000 0.000000 0.000000
0.000000 0.000000 0.000000 0.000000

It does so consistently i.e. it reads only the first two values irregardless of the matrix. In case it is relevant, I'm using Visual Studio Code.


main_gauss.c:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include "linalg.h"

int main(void){
    int n = 3;
    int m = 4;

    /* Allocate memory for matrix A */
    double **A = (double **) malloc(n * sizeof(double *));  // Allocate memory for rows
    for (int i = 0; i < n; i++) {
        A[i] = (double *) malloc(m * sizeof(double));       // Allocate memory for columns
    }

    read_matrix(n, m, A, "Gauss1.dad");

    return 0;
}

linalg.c:

#include "linalg.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void read_matrix(int n, int m, double **A, char *s){
    /* Open the file */
    FILE * file ;
    file = fopen (s, "r");
    if ( file == NULL ){
        printf("Error opening %s\n", ".dad file."); 
        return;
    }

    /* Import data to A */
    printf("\nMatrix A:\n");
    for (int i = 0; i < n; i++){
        for (int j = 0; j < m; j++){
            fscanf(file, "%lf", &A[i][j]);      
            printf("%lf ", A[i][j]);
        }
        printf("\n");
    }
    printf ("\n");
    fclose(file);   // Close the file
}

lingalg.h:

#ifndef LINALG_H
#define LINALG_H

void read_matrix(int n, int m, double **A, char *s);

#endif

Solution

  • You have minus signs in the data, Unicode character 8722. The %lf conversion of fscanf expects a hyphen to represent a minus sign. Edit the Gauss1.dad file to change the minus signs to hyphens. Or edit the code to read the characters (as strings or individual characters, not with %lf) and parse the minus signs.