Я хочу реализовать матричное умножение в c ++. А вот мой код:
#include"math.h";
#include <iostream>
using namespace std;
int** create_matrix(int rows, int cols);
int** calculate_matrix(int** matrix1, int** matrix2, int row_1, int col_1, int row_2, int col_2);
void printMatrix(int** matrix, int rows, int cols);
void main(int argc, char** argv) {
int matrix_A[3][2] = { {1,2},{3,4},{5,6} };
int matrix_B[2][3] = { {1,2,5},{3,4,6} };
int* matrix_A_point = &matrix_A[0][0];
int* matrix_B_point = &matrix_B[0][0];
int** matrix_A_point_final = &matrix_A_point;
int** matrix_B_point_final = &matrix_B_point;
int** new_matrix = calculate_matrix(matrix_A_point_final, matrix_B_point_final, 3, 2, 2, 3);
printMatrix(new_matrix, 3, 3);
}
int** create_matrix(int rows, int cols) {
//create the new matrix
int** matrix = new int* [rows];
for (int i = 0; i < rows; i++) {
matrix[i] = new int[cols];
}
return matrix;
}
int** calculate_matrix(int** matrix1, int** matrix2,int row_1,int col_1,int row_2,int col_2) {
//multiplication the matrixs
int** new_matrix = create_matrix(row_1, col_2);
if (col_1 == row_2) {
cout << "The two matrixs can multiplicate!" << endl;
for (int i = 0; i < row_1; i++) {
for (int j = 0; j < col_2; j++) {
new_matrix[i][j] = 0;
for (int m1_col = 0; m1_col < col_1; m1_col++) {
new_matrix[i][j] = matrix1[i][m1_col] * matrix2[m1_col][j];
}
}
}
}
else {
cout << "The two matrixs can't multiplicate!" << endl;
}
return new_matrix;
}
void printMatrix(int** matrix, int rows, int cols) {
for (int i = 0; i < rows; ++i) {
cout << "the line of: " << i;
for (int j = 0; j < cols; ++j) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
Однако, он сообщает о месте чтения нарушения доступа, когда я запускаю строку: new_matrix [i] [j] = matrix1 [i] [m1_col] * matrix2 [m1_col] [j];
Exception thrown at 0x00007FF6F6DA4997 in Assessment_2.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
Unhandled exception at 0x00007FF6F6DA4997 in Assessment_2.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
Exception thrown at 0x00007FF6F6DA4997 in Assessment_2.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
Unhandled exception at 0x00007FF6F6DA4997 in Assessment_2.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
Exception thrown at 0x00007FF6F6DA4997 in Assessment_2.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
Unhandled exception at 0x00007FF6F6DA4997 in Assessment_2.exe: 0xC0000005: Access violation reading location 0xFFFFFFFFFFFFFFFF.
Кажется, мой второй указатель указывает неверное место. Как справиться с проблемой? Пожалуйста, помогите мне. Спасибо.