二维数组分配、释放
题目描述
-
如果A是个x行y列的矩阵,B是个y行z列的矩阵,把A和B相乘,其结果将是另一个x行z列的矩阵C。这个矩阵的每个元素是由下面的公式决定的:
原型:
voidmatrix_multiply(int *m1,int *m2,int *r, int x, int y, int z);
输入参数:
int *m1:x行y列的矩阵(array1[x][y])
int *m2:y行z列的矩阵(array2[y][z])
int x:矩阵m1的行数
int y:矩阵m1的列数/矩阵m2的行数
int z:矩阵m2的列数
输出参数:
int *r:矩阵m1, m2相乘的结果(array3[x][z])
返回值:
void
输入描述:
输入说明:
1、第一个矩阵的行数
2、第一个矩阵的列数和第二个矩阵的行数
3、第二个矩阵的列数
4、第一个矩阵的值
5、第二个矩阵的值
输出描述:
输出两个矩阵相乘的结果
示例1
输入
2 2 2 3 8 8 0 9 0 18 9
输出
171 72 72 0
代码:
//第六十七题 矩阵乘法
#include<iostream>
using std::cin;
using std::cout;
int main()
{
int first_row, fcol_srow, second_col;
while (cin >> first_row >> fcol_srow >> second_col)
{
int** first, **second, **result;
first = new int*[first_row];//alloc room for first mat
for (int i = 0; i < first_row; i++)
first[i] = new int[fcol_srow];
second = new int*[fcol_srow];//alloc room for second mat
for (int i = 0; i < fcol_srow; i++)
second[i] = new int[second_col];
result = new int*[first_row];//alloc room for result mat
for (int i = 0; i < first_row; i++)
result[i] = new int[second_col];
for (int i = 0; i < first_row; i++)//input data for first mat
for (int j = 0; j < fcol_srow; j++)
cin >> first[i][j];
for (int i = 0; i < fcol_srow; i++)//input data for second mat
for (int j = 0; j < second_col; j++)
cin >> second[i][j];
for (int i = 0; i < first_row; i++)//calculate data for result mat
{
for (int j = 0; j < second_col; j++)
{
int sum = 0;
for (int k = 0; k < fcol_srow; k++)
sum += first[i][k] * second[k][j];
result[i][j] = sum;
}
}
for (int i = 0; i < first_row; i++)
{
for (int j = 0; j < second_col; j++)
cout << result[i][j] << " ";
cout << std::endl;
}
for (int i = 0; i < first_row; i++)
{
delete[] first[i];
first[i] = NULL;
}
delete[] first;
first = NULL;
for (int i = 0; i < first_row; i++)
{
delete[] result[i];
result[i] = NULL;
}
delete[] result;
result = NULL;
for (int i = 0; i < fcol_srow; i++)
{
delete[] second[i];
second[i] = NULL;
}
delete[] second;
second = NULL;
}
return 0;
}