C++使用二级指针、三级指针给函数传参
二级指针用例:
1、定义变量,分配空间,以函数参数的形式传入函数内部,完成处理。
#include<iostream> using namespace std; void fun_C(int a, int b, int **result)//以参数的形式传出(a,b)大小的二维数组 { for (int i = 0; i < a; ++i){ for (int j = 0; j < b; ++j){ result[i][j] = i + j; } } } int main() { int a = 2, b = 3; int **result; //分配空间 result = new int *[a]; for (int i = 0; i<a; i++) { result[i] = new int[b]; } fun_C(a, b, result); //打印 for (int i = 0; i < a; ++i){ for (int j = 0; j < b; ++j){ cout << result[i][j]<<" " ; } cout << endl; } // 释放内存 for (int i = 0; i<a; i++) { delete[] result[i]; } delete[] result; return 0; }
三级指针:
1、定义变量,分配空间,以函数参数的形式传入函数内部,完成处理。
#include<iostream> using namespace std; void fun_C(int a, int b, int c, int ***result){ for (int i = 0; i < a; ++i){ for (int j = 0; j < b; ++j){ for (int k = 0; k < c; ++k){ result[i][j][k] = i+j+k; } } } } int main(){ int a = 2, b = 3, c = 4; int ***result; result = new int **[a]; for (int i = 0; i<a; i++) { result[i] = new int *[b]; for (int j = 0; j<b; j++) result[i][j] = new int[c]; } fun_C(a, b, c, result); for (int i = 0; i < a; ++i){ for (int j = 0; j < b; ++j){ for (int k = 0; k < c; ++k){ cout << result[i][j][k]<<" " ; } cout << endl; } cout << endl; } // 释放内存 for (int i = 0; i<a; i++) { for (int j = 0; j<b; j++) { delete[] result[i][j]; } } for (int i = 0; i<a; i++) { delete[] result[i]; } delete[] result; return 0; }
其实,这些都可以用一维指针去实现,建议使用一维指针。