c++指針和指針的引用,指針的指針的區(qū)別

在打平衡二叉樹時,看別人代碼用到了指針的引用,因?yàn)橹皼]有用過我以為是他多此一舉,但是并不是.
首先是函數(shù)傳遞指針

#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;
}

運(yùn)行結(jié)果:

1.png

在正常情況下我們想要的結(jié)果是2 1
但是輸出卻是2 2;
因?yàn)橹羔榩傳遞到test函數(shù)時接受的是指針,
改變的是形參,而實(shí)參main中指針p沒有發(fā)生變化.
傳遞指針的指針

#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;
}

運(yùn)行結(jié)果:

2.png

這樣結(jié)果就對了.但是兩次解析讓人頭暈.

#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;
}

運(yùn)行結(jié)果: 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


運(yùn)行環(huán)境vs2017

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容