指针
关于指针的介绍和基础应用推荐一位B站up主的视频
1.形参声明为二维数组
以求矩阵最大值为例
#include <bits/stdc++.h>
using namespace std;
const int N = 2;//要改变二维数组的行和列
const int M = 3;//只需改变这里即可
void fun(int array[][M], int, int);
//void fun(int (*array)[M], int, int);//也可这样声明,意义与下面声明为一级指针相同
int main(){
int a[N][M] = {{1, 2, 3}, {4, 5, 6}};
fun(a, N, M);
return 0;
}
void fun(int array[][M], int N, int M)
{
int max = array[0][0];
for (int i = 0; i < N; i ++)
{
for (int j = 0; j < M; j ++)
{
if(max < array[i][j]) max = array[i][j];
}
}
cout << max;
}
2.形参声明为一级指针
以求矩阵最大值为例
#include <bits/stdc++.h>
using namespace std;
const int N = 2;//要改变二维数组的行和列
const int M = 3;//只需改变这里即可
void fun(int* ,int ,int);
int main(){
int a[N][M] = {{1, 2, 3}, {4, 5, 6}};
int *p = a[0];
//定义指针用于储存二维数组第一行的首地址,也就是把二维数组当作一维数组
fun(p, N, M);
//函数调用时传入指针 p
return 0;
}
void fun(int *array, int n, int m){
int max = array[0];
//将 max 预设为数组的第一项
for (int i = 0; i < n * m; i ++){
if(max < array[i]) max = array[i];
}
cout << max;
}
3.形参声明为二级指针
以求矩阵最大值为例
#include <bits/stdc++.h>
using namespace std;
const int N = 2;//要改变二维数组的行和列
const int M = 3;//只需改变这里即可
void fun(int** , int, int);
int main(){
int a[N][M] = {{1, 2, 3}, {4, 5, 6}};
int *p[N];
//定义指针数组用于储存二维数组每行的首地址
p[0] = &a[0][0];
//也可以写为 a[0],目的是令 p 记录下二维数组每一行的首地址
p[1] = &a[1][0];
//也可写为a[1],理由同上
// for(int i = 0; i < N; i ++){//也可写成这样的循环赋指针
// p[i] = &a[i][0];
// //p[i] = a[i];
// }
fun(p, N, M);//函数调用时传入指针 p
return 0;
}
void fun(int **array, int n, int m){
int max = array[0][0];
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if(max < array[i][j]) max = array[i][j];
}
}
cout << max;
}