i am beginner with c++ and i need to make a program to multiply two matrices. I already understand the array of array concept in order to make a dynamic matrix. The problem that im an facing after a make and fill the matrix is that i cannot access it. it suddenly stops when i run the program and just finished filling the second array with the function:
void read_matrix(int** matrix, int row, int col)
{
cout << "Enter a matrix\n";
matrix = new int*[row];
for(int i = 0; i < row; i++)
matrix[i] = new int[col];
if (!matrix){
cerr << "Can't allocate space\n";
}
for(int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
cin >> matrix[i][j];
}
}
}
but according to my compiler, after the program stops there is an arrow pointing after the last loop of this function
void multiply_matrix(int** matrix1, int rows1, int cols1, int** matrix2, int rows2, int cols2, int** result)
{
for(int i = 0; i < rows1; i++){
for(int j = 0; j < cols2; j++){
for (int k = 0; k < rows2; k++){
result[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
my main function is
int main ()
{
//matrices and dimensions
int rows1, cols1, rows2, cols2;
int **matrix1 = 0, **matrix2 = 0, **result = 0;
//TODO: readin matrix dimensions
cout << "Enter matrix dimensions \n";
cin >> rows1 >> cols1 >> rows2 >> cols2;
if(cols1 != rows2){
cout << "Error!";
terminate();
}
//memory for result matrix
result = new int*[rows1];
for(int i = 0; i < rows1; i++)
result[i] = new int[cols2];
// 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;
}
i can not get why it does not work. what i think is there is something wrong in the way i fil the matrix or o do something wrong in the way i send one matrix from one function to the other.
Thanks,
David