Re: [問題] call by pointer
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
→
09/28 23:41, , 1F
09/28 23:41, 1F
→
09/28 23:46, , 2F
09/28 23:46, 2F
→
09/28 23:46, , 3F
09/28 23:46, 3F
→
09/29 00:29, , 4F
09/29 00:29, 4F
推
09/29 01:35, , 5F
09/29 01:35, 5F
→
09/29 01:37, , 6F
09/29 01:37, 6F
推
09/29 11:36, , 7F
09/29 11:36, 7F
→
09/30 22:15, , 8F
09/30 22:15, 8F
→
10/14 14:45, , 9F
10/14 14:45, 9F
→
10/14 15:05, , 10F
10/14 15:05, 10F
→
10/14 15:07, , 11F
10/14 15:07, 11F
→
10/14 15:08, , 12F
10/14 15:08, 12F
→
10/14 15:10, , 13F
10/14 15:10, 13F
→
10/14 15:11, , 14F
10/14 15:11, 14F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 2 之 2 篇):