Earless Earless - 1 month ago 4x
C++ Question

Creating and filling a matrix by input in C++

im trying to write a program in C++ which is able to multiply matrices.
Unfortunately, I'm not able to create a matrice out of 2 vectors. The goal: I typ in the number of rows and the number of coloms. Then there should be a matrix created with those dimensions. Then I can fill (for example rows = 2 cols = 2 => Matrix = 2 x 2) the matrix by typing in the numbers. I tried it with this 2 codes: (second one is in a header file)

#include <iostream>
#include "Matrix_functions.hpp"

using namespace std;

int main ()
//matrices and dimensions
int rows1, cols1, rows2, cols2;
int **matrix1, **matrix2, **result = 0;

cout << "Enter matrix dimensions" << "\n" << endl;
cin >> rows1 >> cols1 >> rows2 >> cols2;

cout << "Enter a matrix" << "\n" << endl;

matrix1 = new int*[rows1];
matrix2 = new int*[rows2];

// Read values from the command line into a matrix
read_matrix(matrix1, rows1, cols1);
read_matrix(matrix2, rows2, cols2);

// Multiply matrix1 one and matrix2, and put the result in matrix result
//multiply_matrix(matrix1, rows1, cols1, matrix2, rows2, cols2, result);

//print_matrix(result, rows1, cols2);

//TODO: free memory holding the matrices

return 0;

This is the main code. Now the header file with the read_matrix function:


void read_matrix(int** matrix, int rows, int cols)
for(int i = 0; i < rows; ++i)
matrix[i] = new int[cols];


//int print_matrix(int result, int rows1, int cols1)
// return 0;

//int multiply_matrix(int matrix2, int rows2, int cols2, int matrix3, int rows3, int cols3, int result2)
// return result2;


The first part works. I can fill in the dimensions. But then it prints: Enter a matrix, and the program quits. Why am I not able to fill in the numbers of the matrix?

I hope someone is able to help me. If there are things unclear, let me know.

Thanks in advance:D
(dont pay attention to most of the comments; those are for the rest of the multiplying code)


You forgot to cin the numbers, try this:

void read_matrix(int** matrix, int rows, int cols)
    for(int i = 0; i < rows; ++i) {
        matrix[i] = new int[cols];
        for(int j = 0; i < cols; ++i) {
            cin >> matrix[i][j];