Reading and Printing a matrix

Leonard Sandu

I tried to read and print a matrix using an external function (from another c file), the thing is that I want to read the matrix dimensions in the function and store them in the main function, how can I do this?

Do I need to return an array with the m and n dimensions of the matrix or can I access the variables that I created in main and change their value within the external function? (I prefer if someone would explain the second) I don't actually know how to use pointers and stuff. Sorry for my English, I'm not a native speaker, also thanks for your response

The second and the third functions are in an external function.c file

int main(){

    int num_of_rows, num_of_columns;
    int matrix[10][10];
    

    read_matrix(num_of_rows, num_of_columns, matrix);
    
    print_matrix(num_of_rows, num_of_columns, matrix);
    

    printf("\n Press any key to exit the program: ");
    _getch();
    return 0;

}


void read_matrix(int num_of_rows, int num_of_columns, int matrix[10][10]){

    int i,j;
  

    printf("\nPlease specify the number of rows:");
    scanf("%d", &num_of_rows);
    printf("\nPlease specify the number of columns: ");
    scanf("%d", &num_of_columns);
    
    printf("\nPlease introduce the matrix elements below:\n");
    for(i=0; i<num_of_rows; i++){
        for(j=0; j<num_of_columns; j++){
            printf("matrix[%d][%d]= ", i, j);
            scanf("%d", &matrix[i][j]);
        }
    }
}


void print_matrix(int num_of_rows, int num_of_columns, int matrix[10][10]){

    int i,j;
   

    for(i=0; i<num_of_rows; i++){
        for(j=0; j<num_of_columns; j++){
            printf("matrix[%d][%d]= %d", i, j, matrix[i][j]);
        }
    }
}
Jabberwocky

Parameters are passed by value in C.

In read_matrix, the num_of_rows parameter is a local variable. Even if you modify it, the caller won't see anything change. Same for num_of_columns.

You want this:

void read_matrix(int *num_of_rows, int *num_of_columns, int matrix[10][10]) {
  //                 ^ add *           ^ add *
  ...
  scanf("%d", num_of_rows);    // << remove the &
  printf("\nPlease specify the number of columns: ");
  scanf("%d", num_of_columns); // << remove the &
  ...

  for (i = 0; i < *num_of_rows; i++) {
    //            ^add *
    for (j = 0; j < *num_of_columns; j++) {
      //            ^add *

and in main:

read_matrix(&num_of_rows, &num_of_columns, matrix);
//          ^             ^ add the &s

This is basic knowledge that is covered in your C learning material. Most likely in the chapter dealing with pointers and the one dealing with function calls.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related