作者wu110011 (不下棋)
看板C_and_CPP
標題Re: [問題] call by pointer
時間Mon Sep 28 23:33:43 2015
http://www.codeproject.com/Articles/4894/Pointer-to-Pointer-and-Reference-
to-Pointer
上面網址文章有提到為什麼要用Pointer to Pointer的原因
我看不太懂,似乎是func()裡pInt裡指向g_One的Address,
回傳的值卻沒有改變,所以要寫成Pointer to Pointer的方式,
那改寫成下面func1()的方式,不就可以回傳Value了嗎?
何必大費周章寫成Pointer to Pointer呢?
//global variable
int g_One = 1;
void func(int* pInt)
{
pInt = &g_One;//只是改變pInt的Address
}
void func1(int* pInt)
{
*pInt = g_One;//改變pInt的Value
}
另外他func pointer to pointer方式的寫法為何要這樣寫呢?
void func(int** ppInt)
{
//Modify the pointer, ppInt points to
*ppInt=&g_One;
//You can also allocate memory, depending on your requirements
*ppInt=new int;
//Modify the variable, *ppInt points to
**ppInt=3;
}
※ 引述《wu110011 (不下棋)》之銘言:
: 開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
: C++
: 問題(Question):
: //global variable
: int g_One=1;
: void foo(int *x) {
: (*x)++; // 指向,並加1
: }
: void foo_2(int *y) {
: y = &g_One;
: }
: int main()
: {
: int x1 = 5;
: foo(&x1);
: std::cout<<x1<<std::endl; //x1的值為6
: foo_2(&x1);
: std::cout<<x1<<std::endl; //x1的值還是為6,沒有變成1
: system("pause");
: return 0;
: }
: 我想問一下,為什麼執行foo(&x1)後,區域變數int *x的值有回傳給x1
: 而執行foo_2(&x1)後,區域變數int *y的值卻沒回傳給x1呢?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.83.23.227
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1443454427.A.B98.html
→ Feis: 錯誤好多阿. :X 09/28 23:41
→ s89227: 你要不要先把所有變數記憶體的示意圖畫出來再想想看? 09/28 23:46
→ s89227: 感覺你好像有點被指標們弄混了 09/28 23:46
→ AIGecko: 門牌和房子是不一樣的 09/29 00:29
推 stupid0319: 感覺你含數的部份都還不是很懂的樣子 09/29 01:35
→ stupid0319: 寫兩個**連在一起,基本上我也看不懂要表達什麼QQ 09/29 01:37
推 Ninja5566: foo_2 所取的pointer為是經過複製的 pointer 09/29 11:36
→ james1022jk: 樓上已經說明了... 09/30 22:15
→ ARies77: 補充一個觀念:所謂的 pass by pointer = pass by value 10/14 14:45
→ ARies77: 以那例子來說func(int** ppInt)傳進去複製的指標是&pvar 10/14 15:05
→ ARies77: 而pvar存的資料是g_One的指標,這指標存的資料是g_One 10/14 15:07
→ ARies77: 所以,參數ppInt=&pvar,*ppInt=pvar,**ppInt=*pvar 10/14 15:08
→ ARies77: 就能達到function內改指標跟資料的目的,ref to ptr同義 10/14 15:10
→ ARies77: 實際一步一步做 %d %p 的輸出來看,就很容易理解了 10/14 15:11