向函数传递指针不会返回值
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;
}
您将地址分配给指针,而不是将值分配给所指向的。像这样试试
int demo (int *NumRecPrinted)
{
int no_of_records = 11;
*NumRecPrinted = no_of_records;
}
否!
*NumRecPrinted = no_of_records;
请参阅"*"表示"的值","&"表示"地址"。您想要更改NumRecPrinted的"值",这就是为什么上面的工作原理。您所做的是将num_of_records的"地址"提供给NumRecPrinted。
您所做的只是将本地指针指向demo
函数内的一个新整数处的intNumRecPrinted
。
您要更改它指向的整数,而不是更改它指向哪里。
*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"。
相关文章:
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 当我使用 void 函数的返回值(通过强制转换函数指针)时,究竟会发生什么?
- 如何在不使用临时变量的情况下取消引用返回指针的函数的返回值?
- 如何返回值为NULL的变量指针
- 将指向数组的指针作为函数参数传递,这本身就是另一个函数的返回值?
- 为什么 c_str() 在返回常量指针值时不输出地址
- 存储指向函数返回值的指针
- 指针未正确返回值
- 动态指针引用数组由三元运算符返回值,但有异常
- 指针返回值的地址
- 将指针设置为函数的返回值
- 即使在返回值之前释放后,数据仍在指针中仍然存在
- 返回指针、返回值或传入引用,这在C++中很优雅
- 为什么静态、非本地返回指针的返回值始终为零?
- 从共享指针矢量字符串返回值
- 当函数返回值是指针,而返回类型是c++中的引用时会发生什么
- 为什么指针返回值,而不是地址
- 返回指向常量getter的指针时,返回值类型与函数类型不匹配
- 是指向在向函数返回值/参数和类请求传输数据期间复制的内存的指针
- 作为 c++ dll 函数返回值的结构指针