影醉阏轩窗

衣带渐宽终不悔,为伊消得人憔悴。
扩大
缩小

全局指针变量做形参

 


 

  今天遇到一个特别奇怪的现象,以前都是说“指针”、“引用”做参数可以不用return去返回,会直接改变参数的值,但是今天让我找了很大的功夫才知道原因。

  正常的情况咱们就不说了,太简单了,比如正常的int num; void test(int c)做参数,那么肯定不会改变num的值。因为你知道没用&或者*.

1.全局变量指针做参数:

  这个是指针吧?这个又是全局变量吧?为什么结果却不能更新呢?

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int *p = NULL;//全局变量
 5 
 6 void test(int *c)
 7 {
 8     int num = 10;
 9     c = &num;
10 }
11 
12 int main()
13 {
14     test(p);
15     return 0;
16 }

2.全局变量做参数

  全局变量非指针,做参数之后还是没办法改变值?

 

 1 #include<iostream>
 2 using namespace std;
 3 
 4 int p = 1;//全局变量
 5 
 6 void test(int *c)
 7 {
 8     int num = 10;
 9     c = &num;
10 }
11 void test1(int c)
12 {
13     int num = 10;
14     c = num;
15 }
16 int main()
17 {
18     test1(p);
19     return 0;
20 }

 

3.局部变量做参数

  局部变量指针和非指针都不行,大家自行测试!

 

 1 #include<iostream>
 2 using namespace std;
 3 
 4 //int p = 1;//全局变量
 5 
 6 void test(int *c)
 7 {
 8     int num = 10;
 9     c = &num;
10 }
11 void test1(int c)
12 {
13     int num = 10;
14     c = num;
15 }
16 int main()
17 {
18     int *p = NULL;
19     test(p);
20     return 0;
21 }

 

4.解决方法

  之前我们说的指针和引用做参数,指的是这个参数本身变为指针或者引用,而不是这个参数本身是什么!

  两种方法解决,把参数变成指针或者引用!

使用引用:

 1 #include<iostream>
 2 using namespace std;
 3 
 4 //int p = 1;//全局变量
 5 
 6 void test(int* &c)
 7 {
 8     int num = 10;
 9     c = &num;
10 }
11 void test1(int &c)
12 {
13     int num = 10;
14     c = num;
15 }
16 int main()
17 {
18     int *p = NULL;
19     test(p);
20     return 0;
21 }

使用指针:

 1 #include<iostream>
 2 using namespace std;
 3 
 4 //int p = 1;//全局变量
 5 
 6 void test(int** c)
 7 {
 8     int num = 10;
 9     *c = &num;
10 }
11 void test1(int *c)
12 {
13     int num = 10;
14     c = &num;
15 }
16 int main()
17 {
18     int *p = NULL;
19     test(&p);
20     return 0;
21 }

 

参考:受到这篇博文的启发,突然明白过来这么回事。http://blog.csdn.net/menyangyang/article/details/38964549

posted on 2018-01-29 16:50  影醉阏轩窗  阅读(711)  评论(0编辑  收藏  举报

导航

/* 线条鼠标集合 */ /* 鼠标点击求赞文字特效 */ //带头像评论