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

示例

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

 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

 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

 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

 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

 

 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

总结

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

参考

关于双重指针的用法

https://blog.csdn.net/wjy397/article/details/82794380

剑指offer 面试题18:删除链表节点

https://www.cnblogs.com/cxc1357/p/12027597.html

参数传递

https://www.cnblogs.com/cxc1357/p/11945728.html

原文地址:https://www.cnblogs.com/cxc1357/p/13151620.html