私は C++ の初心者で、2 つの行列を乗算するプログラムを作成する必要があります。動的行列を作成するための配列の配列の概念は既に理解しています。マトリックスを作成して埋めた後に直面している問題は、それにアクセスできないことです。プログラムを実行すると突然停止し、関数で2番目の配列を埋め終わったところです:
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];
}
}
}
しかし、私のコンパイラによると、プログラムが停止した後、この関数の最後のループの後に矢印があります
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];
}
}
}
私の主な機能は
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;
}
なぜ機能しないのかわかりません。私が思うのは、マトリックスをフィルする方法に何か問題があるか、ある関数から別の関数にマトリックスを送信する方法に何か問題があると思います。
ありがとう、
デビッド