示例

  •  将值(实参)传递给值(形参),无法更改val

[c++] 二级指针的原理_ios

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void change(int mem){
 5     mem = 2;
 6 }
 7 
 8 int main(){
 9     int val;
10     val = 1;
11     cout << val << endl;
12     change(val);
13     cout << val << endl;
14     return 0;
15 }

1

1

  • 将地址(实参)传递给指针(形参),可以更改val

[c++] 二级指针的原理_ios_02

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void change(int *mem){
 5     *mem = 2;
 6 }
 7 
 8 int main(){
 9     int val;
10     val = 1;
11     cout << val << endl;
12     change(&val);
13     cout << val << endl;
14     return 0;
15 }

1

2

  •  将值(实参)传递给引用(形参),可以更改val

[c++] 二级指针的原理_ios_03

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void change(int &mem){
 5     mem = 2;
 6 }
 7 
 8 int main(){
 9     int val;
10     val = 1;
11     cout << val << endl;
12     change(val);
13     cout << val << endl;
14     return 0;
15 }

1

2

  • 将指针(实参)传递给指针(形参),无法更改str

[c++] 二级指针的原理_#include_04

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void change(const char *pstr){
 5     pstr = "banana";
 6 }
 7 
 8 int main(){
 9     const char *str;
10     str = "apple";
11     cout << str << endl;
12     change(str);
13     cout << str << endl;
14     return 0;
15 }

apple

apple

  • 将指针的地址(实参)传递给二级指针(形参),可更改str

 [c++] 二级指针的原理_剑指offer_05

 1 #include <iostream>
 2 using namespace std;
 3 
 4 void change(const char **pstr){
 5     *pstr = "banana";
 6 }
 7 
 8 int main(){
 9     const char *str;
10     str = "apple";
11     cout << str << endl;
12     change(&str);
13     cout << str << endl;
14     return 0;
15 }

apple

bababa

总结

  • 可见,想通过函数改变函数外的变量,需要传址而不是传值
  • 为什么使用二级指针呢,因为实参和形参类型必须对应,想改变指针的值,就要传递指针的地址,即二级指针