[英]Passing pointers to function does not return value
In following case I get NumRecPrinted = 0 , that is num is 0 在下面的例子中,我得到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;
}
No! 没有!
*NumRecPrinted = no_of_records;
See "*" means "value of" and "&" means "address of". 参见“*”表示“值”,“&”表示“地址”。 You want to change the "value of" NumRecPrinted, which is why the above works. 您想要更改NumRecPrinted的“值”,这就是上述工作原因。 What you did was to give NumRecPrinted the "address of" num_of_records. 你做的是给NumRecPrinted“num_of_records的地址”。
You are assigning the address to the pointer, and not the value to the pointed-to. 您正在为指针分配地址,而不是指向指向的值。 Try it like this instead 试试这样吧
int demo (int *NumRecPrinted)
{
int no_of_records = 11;
*NumRecPrinted = no_of_records;
}
All you did was pointer the local pointer-to-int NumRecPrinted
at a new integer inside the demo
function. 你所做的就是将本地指针指向 NumRecPrinted
指针指向 demo
函数内的一个新整数。
You want to change the integer it points to, not change where it points. 您想要更改它指向的整数,而不是更改它指向的位置。
*NumRecPrinted = no_of_records;
You can see in your version that you're taking the address of a local variable, and you know it isn't the address of that variable you care about, but its value. 你可以在你的版本,你正在做一个局部变量的地址看看 ,你知道这是不是你关心的是变量的地址,但它的价值。
As others have pointed out, the * = the value of and & = address of. 正如其他人所指出的,* =和=的地址的值。 So you were just assigning a new address to the pointer inside the method. 所以你只是为方法内的指针分配一个新地址。 You should: 你应该:
*NumRecPrinted = no_of_records;
See this excellent tutorial on Pointers . 请参阅这个关于指针的优秀教程。 Eg: 例如:
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
You want *NumRecPrinted = no_of_records; 你想要* NumRecPrinted = no_of_records;
That means, "set the thing NumRecPrinted points to to equal no_of_records". 这意味着,“将NumRecPrinted点数设置为等于no_of_records”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.