[英]Passing pointers to function does not return value
在下面的例子中,我得到NumRecPrinted = 0,即num為0
int main()
{
int demo(int *NumRecPrinted);
int num = 0;
demo(&num);
cout << "NumRecPrinted=" << num; <<<< Prints 0
return 0;
}
int demo (int *NumRecPrinted)
{
int no_of_records = 11;
NumRecPrinted = &no_of_records;
}
沒有!
*NumRecPrinted = no_of_records;
參見“*”表示“值”,“&”表示“地址”。 您想要更改NumRecPrinted的“值”,這就是上述工作原因。 你做的是給NumRecPrinted“num_of_records的地址”。
您正在為指針分配地址,而不是指向指向的值。 試試這樣吧
int demo (int *NumRecPrinted)
{
int no_of_records = 11;
*NumRecPrinted = no_of_records;
}
你所做的就是將本地指針指向 NumRecPrinted
指針指向 demo
函數內的一個新整數。
您想要更改它指向的整數,而不是更改它指向的位置。
*NumRecPrinted = no_of_records;
你可以在你的版本,你正在做一個局部變量的地址看看 ,你知道這是不是你關心的是變量的地址,但它的價值。
正如其他人所指出的,* =和=的地址的值。 所以你只是為方法內的指針分配一個新地址。 你應該:
*NumRecPrinted = no_of_records;
請參閱這個關於指針的優秀教程。 例如:
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;
p1 = &firstvalue; // p1 = address of firstvalue
p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
你想要* NumRecPrinted = no_of_records;
這意味着,“將NumRecPrinted點數設置為等於no_of_records”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.