In: Computer Science
Solution
/*** matrix.h ***/
#ifndef MATRIX_H
#define MATRIX_H
//Matrix structure definition
typedef struct
{
unsigned rows;
unsigned columns;
double **data;
}Matrix;
//function prototypes
Matrix create_matrix(unsigned r, unsigned c);
void print_matrix(Matrix mat);
void free_matrix(Matrix mat);
#endif // MATRIX_H
/*** matrix.c ***/
#include <stdio.h>
#include <stdlib.h>
#include"matrix.h"
//function to create Matrix
Matrix create_matrix(unsigned rows, unsigned columns)
{
Matrix mat;
mat.columns = columns;
mat.rows = rows;
mat.data =(double**)malloc(rows * sizeof(double*));
double *q =(double*)malloc(rows * columns * sizeof(double));
for(unsigned i=0; i<rows; i++)
{
mat.data[i] = q;
q += columns;
}
for(unsigned i=0; i<rows; i++)
for(unsigned j=0; j<columns; j++)
mat.data[i][j] = 0.0;
return mat;
}
//function to print the Matrix
void print_matrix(Matrix mat)
{
for(unsigned i=0; i<mat.rows; i++){
for(unsigned j=0; j<mat.columns; j++)
printf("%0.6f ", mat.data[i][j]);
printf("\n");
}
}
//function to free the Matrix
void free_matrix(Matrix mat)
{
for(unsigned i=0; i<mat.rows; i++)
{
free(mat.data[i]);
}
free(mat.data);
}
/*** main.cpp */
#include <stdio.h>
#include <stdlib.h>
#include"matrix.h"
//main function
int main()
{
int rows = 3;
int columns = 3;
Matrix mat = create_matrix(rows, columns);
print_matrix(mat);
free_matrix(mat);
return 0;
}
Output:
Solving your question and
helping you to well understand it is my focus. So if you face any
difficulties regarding this please let me know through the
comments. I will try my best to assist you. However if you are
satisfied with the answer please don't forget to give your
feedback. Your feedback is very precious to us, so don't give
negative feedback without showing proper reason.
Always avoid copying from existing answers to avoid
plagiarism.
Thank you.