请检查上面代码是否有问题
上面代码存在以下问题:
- 函数multiplication中的return语句应该放在for循环外面,否则只会计算一次并返回结果。
- 二维数组传参应该使用指针或者引用的方式,而不是直接使用数组名。
- 当aM或bN为0时,result数组没有被成功创建,而主函数中的print函数会尝试打印这个未定义的数组,会导致错误。
修改后的代码如下:
#include
int** multiplication(int** a, int aM, int aN, int** b, int bM, int bN) { if (aN != bM || aM == 0 || bN == 0) { return nullptr; } //创建结果数组 int **result = new int *[aM]; for (int i = 0; i < aM; i++) { result[i] = new int[bN]; } for (int i = 0; i < aM; i++) { for (int j = 0; j < bN; ++j) { result[i][j] = 0; for (int k = 0; k < aN; k++) { result[i][j] += a[i][k] * b[k][j]; } } } return result; }
void print(int** a, int aM, int aN){ for (int i = 0; i < aM; ++i) { for (int j = 0; j < aN; ++j) { cout<<a[i][j]<<" "; } cout<<endl; } }
int main() { int a[3][4]={ {2,6,5,9}, {4,5,8,5}, {6,9,0,1}, }; int b[4][3]={ {2,6,5}, {6,5,8}, {6,9,10}, {8,6,4} }; int** result=multiplication((int**)a,3,4,(int**)b,4,3); if (result != nullptr) { print(result,3,3); for (int i = 0; i < 3; i++) { delete [] result[i]; } delete [] result; } return 0; }
原文地址: https://www.cveoy.top/t/topic/dZn 著作权归作者所有。请勿转载和采集!