③输入一个4行3列的二维矩阵,编写一个函数用于显示此矩阵元素的值,要求实现使用二维数组和指针作为形参两种方法。
时间: 2024-03-10 10:48:43 浏览: 19
好的,以下是使用二维数组和指针作为形参两种方法的实现代码:
1. 使用二维数组作为形参:
```c++
#include <iostream>
using namespace std;
void displayMatrix(int matrix[][3], int rows) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
}
int main() {
int myMatrix[4][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
displayMatrix(myMatrix, 4);
return 0;
}
```
2. 使用指针作为形参:
```c++
#include <iostream>
using namespace std;
void displayMatrix(int *matrix, int rows, int cols) {
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
cout << *(matrix + i*cols + j) << " ";
}
cout << endl;
}
}
int main() {
int myMatrix[4][3] = {{1, 2, 3},
{4, 5, 6},
{7, 8, 9},
{10, 11, 12}};
displayMatrix(&myMatrix[0][0], 4, 3);
return 0;
}
```
注意,这里使用了指针来代替二维数组作为形参,因为在 C++ 中,函数形参中的数组是以指针的形式传递的。在第二个示例中,我们将 `&myMatrix[0][0]` 作为参数传递给函数,这是一个指向矩阵中第一个元素的指针。在函数中,我们使用 `(matrix + i*cols + j)` 来访问矩阵中的元素,其中 `matrix` 是指向第一个元素的指针,`i` 和 `j` 分别是行和列的索引。