【发布时间】:2013-09-10 20:17:40
【问题描述】:
我是 C++ 的初学者,我需要编写一个程序来将两个矩阵相乘。为了制作动态矩阵,我已经了解了数组的概念。我在制作和填充矩阵后面临的问题是我无法访问它。当我运行程序并用函数填充第二个数组时它突然停止:
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;
}
我不明白为什么它不起作用。我认为我填充矩阵的方式有问题,或者我将一个矩阵从一个函数发送到另一个函数的方式有问题。
谢谢,
大卫
【问题讨论】:
-
您可能了解动态数组,但您不了解参数传递。
void read_matrix(int** matrix, int row, int col); ... int **matrix1 = 0; ... read_matrix(matrix1, rows1, cols1);不会改变matrix1的值。更改发生在read_matrix函数内部,main 中matrix1的值完全不受影响。即使你调用了read_matrix,它仍然是0。如果你想要一个函数返回一个值,那么使用return,或者使用引用。
标签: c++ arrays function dynamic matrix