I am trying to write 2 functions, one for reading a matrix (2D array) and another for printing it. So far, I:
double **read_matrix(int rows, int cols){ double **mat = (double **) malloc(sizeof(double *)*rows); int i=0; for(i=0; i<rows; i++){ mat[i] = (double *) malloc(sizeof(double)*cols);
then the print matrix function, not sure if it is correct
void print_matrix(int rows, int cols, double **mat){ for(i=0; i<rows; i++){ for(j=0; j<cols; j++){ printf("%f ",mat[i][j]); } }}
and here is the main function that I use to run:
#include <stdio.h> #include <stdlib.h> double **read_matrix(int rows, int cols); void print_matrix(int rows, int cols, double **mat); void free_matrix(int rows, double **mat); int main(){ double **matrix; int rows, cols; /* First matrix */ printf("Matrix 1\n"); printf("Enter # of rows and cols: "); scanf("%d %d",&rows,&cols); printf("Matrix, enter %d reals: ",rows*cols); matrix = read_matrix(rows,cols); printf("Your Matrix\n"); /* Print the entered data */ print_matrix(rows,cols,matrix); free_matrix(rows, matrix); /* Free the matrix */ return 0;}
source share