动态二维存储空间的应用,要求: (1)定义函数,从键盘输入二维空间的行数和列数,动态分配二 维整型存储空间。 (2)定义函数,实现对两个二维数组元素的加和(矩阵的相加), 结果返回另一个二维数组。
时间: 2023-04-12 19:01:51 浏览: 50
好的,我可以回答这个问题。以下是代码示例:
#include <iostream>
using namespace std;
int** allocateSpace(int rows, int cols) {
int** arr = new int*[rows];
for(int i = 0; i < rows; i++) {
arr[i] = new int[cols];
}
return arr;
}
int** addArrays(int** arr1, int** arr2, int rows, int cols) {
int** result = allocateSpace(rows, cols);
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
result[i][j] = arr1[i][j] + arr2[i][j];
}
}
return result;
}
int main() {
int rows, cols;
cout << "Enter number of rows: ";
cin >> rows;
cout << "Enter number of columns: ";
cin >> cols;
int** arr1 = allocateSpace(rows, cols);
int** arr2 = allocateSpace(rows, cols);
cout << "Enter values for array 1:" << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cin >> arr1[i][j];
}
}
cout << "Enter values for array 2:" << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cin >> arr2[i][j];
}
}
int** result = addArrays(arr1, arr2, rows, cols);
cout << "Result:" << endl;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cout << result[i][j] << " ";
}
cout << endl;
}
return 0;
}
希望这可以帮到你!
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)