在打平衡二叉树时,看别人代码用到了指针的引用,因为之前没有用过我以为是他多此一举,但是并不是.
首先是函数传递指针
#include<iostream>
using namespace std;
int a = 1;
void test(int *p)
{
p = &a;
}
int main()
{
int d = 2;
int *p = &d;
cout << *p << endl;
test(p);
cout << *p << endl;
}
运行结果:

在正常情况下我们想要的结果是2 1
但是输出却是2 2;
因为指针p传递到test函数时接受的是指针,
改变的是形参,而实参main中指针p没有发生变化.
传递指针的指针
#include<iostream>
using namespace std;
int a = 1;
void test(int **p)
{
*p = &a;//一次解析,是被指向指针的指针
}
int main()
{
int d = 2;
int *p = &d;
cout << *p << endl;
test(&p);//将*p的地址穿入test
cout << *p << endl;
}
运行结果:

这样结果就对了.但是两次解析让人头晕.
#include<iostream>
using namespace std;
int a = 1;
void test(int *&p)//对main中*p的引用
{
p = &a;
}
int main()
{
int d = 2;
int *p = &d;
cout << *p << endl;
test(p);
cout << *p << endl;
}
运行结果: 2 1
想起来c++ primer书上刚讲引用的例子
string a="i''m a good boy"
for(auto s:a)
toupper(s);
cout<<a<<endl;
这样a不会变,如果用auto &s的话就说输出I'M A COOL GOOD BOY
运行环境vs2017
网友评论