利用指针计算两个矩阵的和
时间: 2024-05-16 19:13:28 浏览: 47
假设有两个矩阵A和B,它们的行数和列数均相等,我们可以使用指针计算它们的和。具体步骤如下:
1. 定义两个指向矩阵的指针A_ptr和B_ptr,以及一个指向结果矩阵的指针C_ptr。
2. 使用动态内存分配函数分别为A、B、C分配内存。
3. 使用两层循环遍历矩阵A和B的每个元素,将它们的和存储到矩阵C中。
4. 最后,释放分配的内存。
下面是代码示例:
```c++
#include <iostream>
using namespace std;
int main() {
int rows, cols;
cout << "Enter the number of rows and columns for the matrices: ";
cin >> rows >> cols;
// Allocate memory for matrices
int** A = new int*[rows];
int** B = new int*[rows];
int** C = new int*[rows];
for (int i = 0; i < rows; i++) {
A[i] = new int[cols];
B[i] = new int[cols];
C[i] = new int[cols];
}
// Input values for matrices A and B
cout << "Enter the values for matrix A: " << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> A[i][j];
}
}
cout << "Enter the values for matrix B: " << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cin >> B[i][j];
}
}
// Calculate matrix sum
int** A_ptr = A;
int** B_ptr = B;
int** C_ptr = C;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
**C_ptr = **A_ptr + **B_ptr; // Calculate sum
A_ptr++; // Move pointers to next element
B_ptr++;
C_ptr++;
}
A_ptr -= cols; // Move pointers to next row
B_ptr -= cols;
C_ptr -= cols;
}
// Print result matrix
cout << "Result matrix C = A + B:" << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
cout << C[i][j] << " ";
}
cout << endl;
}
// Deallocate memory for matrices
for (int i = 0; i < rows; i++) {
delete[] A[i];
delete[] B[i];
delete[] C[i];
}
delete[] A;
delete[] B;
delete[] C;
return 0;
}
```
阅读全文