I tried to print a matrix based on this code but somehow it causes a segmentation fault. I want to transfer the given arrays to the struct member data and then print them out by referecing to data. I scanned through it but I cannot find my mistake. Maybe I messed up when allocating memory for the structure.
#include "base.h"
struct Matrix {
int rows; // number of rows
int cols; // number of columns
double** data; // a pointer to an array of n_rows pointers to rows; a row is an array of n_cols doubles
};
typedef struct Matrix Matrix;
Matrix* make_matrix(int n_rows, int n_cols) {
Matrix* mat = xcalloc(n_rows,sizeof(double*));
mat->rows = n_rows;
mat->cols = n_cols;
return mat;
}
Matrix* copy_matrix(double* data, int n_rows, int n_cols) {
Matrix* mat = make_matrix(n_rows, n_cols);
for(int i = 0; i < (mat->rows); i++)
{
for(int j = 0; j < (mat->cols); j++)
{
mat->data[i][j] = data[i] + j;
}
}
return mat;
}
void print_matrix(Matrix* m)
{
for(int i = 0; i < (m->rows); i++)
{
for(int j = 0; j < (m->cols); j++)
{
printf("%g", m->data[i][j]);
}
}
}
void matrix_test(void) {
double a[] = {
1, 2, 3,
4, 5, 6,
7, 8, 9 };
Matrix* m1 = copy_matrix(a, 3, 3);
print_matrix(m1);
double a2[] = {
1, 2, 3,
4, 5, 6 };
Matrix* m2 = copy_matrix(a2, 2, 3);
print_matrix(m2);
double a3[] = {
1, 2,
3, 4,
5, 6 };
Matrix* m3 = copy_matrix(a3, 3, 2);
print_matrix(m3);
}