Catalin Ghita Catalin Ghita - 7 days ago 4
C Question

Reading and printing matrix in C

Ok so my main goal is to multiply two matrices.Before jumping there i proposed myself to write 2 functions to read and display a matrix. Basic stuff i thought.
After i run the program and i enter the number of lines and columns,i can only enter 1 value before it crashes.
I use Dev c++.
What could the issue be here? Thank you in advance.

#include <stdio.h>
#define MAXSIZE 20
void readM(int M[MAXSIZE][MAXSIZE],int,int);
void printM(int M[MAXSIZE][MAXSIZE],int,int);

int main ()

{
int NL,NC,i,j;
int M[20][20];
readM(M[20][20],NL,NC);
printM(M[20][20],NL,NC);


return 0;
}


void readM(int M[20][20],int NL,int NC)
{
int i,j;
printf("Type in number lines ");
scanf("%d",&NL);
printf("Type in number of columns ");
scanf("%d",&NC);
printf("Type in values \n");

for(i=0;i<NL;i++)
{
for(j=0;j<NC;j++)
{
scanf("%d",&M[i][j]);
}
}
}

void printM(int M[20][20],int NL,int NC)
{
int i,j;
printf("Matrix is \n");

for(i=0;i<NL;i++)
{
for(j=0;j<NC;j++)
{
printf("\t%d\t",M[i][j]);
}
printf("\n");
}
}

Answer

First, when you call readM and printM, you should call them using M, not M[20][20].

Then, there's the lines and columns problem. When you pass the arguments NL and NC to readM, you're passing a copy of their values inside main. When you read the values in readM you'll store what you read locally, and main will never know about it.

To change that, you could use pointers or you could read the lines and columns in main, leaving readM with the sole purpose of reading matrix itens.

The program may be skipping your input because there's trash in the input buffer. The best way of getting user input is creating a custom function that reads whatever there is in stdin, and then treat it accordingly. Because you never know what users will input...

Here's the code with my suggestions:

#include <stdio.h>
#include <stdlib.h>

#define MAXSIZE 20

void readM(int M[MAXSIZE][MAXSIZE], int, int);
void printM(int M[MAXSIZE][MAXSIZE], int, int);

/* very simple function to treat user input */
int read_num(void)
{
    char buf[50];
    fgets(buf, 50, stdin);
    return atoi(buf);
}

/* if main() won't take any arguments, use void */
int main(void)
{
    int NL, NC, i, j;
    int M[20][20];

    /* extracted from readM */
    printf("Type in number lines ");
    NL = read_num();
    printf("Type in number of columns ");
    NC = read_num();

    readM(M, NL, NC);

    printM(M, NL, NC);


    return 0;
}


void readM(int M[MAXSIZE][MAXSIZE], int NL, int NC)
{
    int i, j;
    printf("Type in values \n");

    for (i = 0; i < NL; i++) {
        for (j = 0; j < NC; j++) {
            M[i][j] = read_num();
        }
    }
}

void printM(int M[MAXSIZE][MAXSIZE], int NL, int NC)
{
    int i, j;
    printf("Matrix is \n");

    for (i = 0; i < NL; i++) {
        for (j = 0; j < NC; j++) {
            printf("\t%d\t", M[i][j]);
        }
        printf("\n");
    }
}