【发布时间】:2015-10-19 15:28:15
【问题描述】:
考虑下面我尝试以 C 方式传递引用的示例:
// Function prototypes
void increment(unsigned* number);
int main()
{
unsigned* thing;
increment(thing);
cout << *thing;
return 0;
}
void increment(unsigned* number)
{
number = (unsigned*) malloc(sizeof(unsigned));
*number = 1;
}
我在cout << *thing 行遇到程序崩溃。是的,我在这里使用 C++,但我想尝试 C 版本的传递引用,因为我的主要项目是 C 语言。
我通过如下更改代码来修复它:
// Function prototypes
void increment(unsigned** number);
int main()
{
unsigned* thing;
increment(&thing);
cout << *thing;
return 0;
}
void increment(unsigned** number)
{
*number = (unsigned*) malloc(sizeof(unsigned));
**number = 1;
}
现在它可以工作了,输出为 1,就像我预期的那样。但是,我不明白为什么。我有点困惑为什么在顶部分层一个额外的指针可以解决我的问题。
谢谢!
【问题讨论】:
-
黄金法则:参数总是按值传递。您只更新了指针的本地副本。它没有传播回调用者,因为它是按值传递的,kaboom。请注意在工作版本中您没有更改 number 参数的方式。你改变了 *number,就像你应该做的那样。
-
我正在开发一个与嵌入式 C 对话的 C++ 应用程序,我认为这就是它令人困惑的原因。
-
C 不支持按引用传递。
-
VS-compiler 接受 C 的引用传递
标签: c memory-management memory-leaks pass-by-reference