困惑传递通过引用 [英] Confused on pass-by-reference

查看:145
本文介绍了困惑传递通过引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在我试图传递通过引用在C方式下面的例子:

Consider the below example where I am attempting to pass-by-reference in the C way:

// 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℃的程序崩溃;&LT; *事情。是的,我使用C ++在这里,但我想尝试的传递通过引用,因为我的主要项目是用C,C版

I get a program crash at the line cout << *thing. Yes, I am using C++ here but I wanted to try out the C version of pass-by-reference because my main project is in C.

我通过改变code如下固定的:

I fixed it by changing the code as follows:

// 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,像我的预期。不过,我不明白为什么。我有点困惑,为什么在上面分层额外的指针可以解决我的问题。

And now it works and the output is 1, like I expected. However, I do not understand why. I'm a bit confused as to why layering an extra pointer on top solves my problem.

谢谢!

推荐答案

C没有通通过引用。除了阵列,所有的参数都是按值传递的。

C doesn't have pass-by-reference. Except for arrays, all parameters are passed by value.

在你的第一个版本,你按值传递变量的事情。在递增的功能,它分配内存并分配给本地变量数量。但是这对呼叫者的变量没有影响,因为只有其值被传递,而不是对变量的引用。因此,的事情还是当递增回报,并通过indirecting它导致不确定的行为未初始化。

In your first version, you're passing the variable thing by value. In the increment function, it allocates memory and assigns that to the local variable number. But this has no effect on the caller's variable, because only its value was passed, not a reference to the variable. So thing is still uninitialized when increment returns, and indirecting through it results in undefined behavior.

如果一个函数需要修改呼叫者的变量,调用者具有对指针传递给变量,而不仅仅是值。这就是你的第二个版本做了什么。然后该函数可以间接通过指针来更新变量

If a function needs to modify a caller's variable, the caller has to pass a pointer to the variable, not just the value. That's what you did in the second version. Then the function can indirect through the pointer to update the variable.

这基本上是发生了什么事情在幕后,当你用C使用引用++。在C语言中,你必须code间接明确了额外级别。

This is essentially what's going on under the covers when you use references in C++. In C you have to code the extra level of indirection explicitly.

这篇关于困惑传递通过引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆