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

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

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

 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

相关文章:

  • 2021-09-08
  • 2021-07-20
  • 2022-12-23
  • 2021-06-19
  • 2021-11-09
  • 2021-07-14
  • 2021-12-26
  • 2021-10-17
猜你喜欢
  • 2021-10-15
  • 2021-10-08
  • 2021-09-08
  • 2021-05-28
  • 2021-11-20
  • 2022-12-23
  • 2021-10-04
相关资源
相似解决方案