用C按引用传递过程中会发生什么? [英] what happens during pass by reference in C?
问题描述
我知道,当我们通过一个参数在函数的堆栈中创建一个副本的功能并没有在调用者的函数参数的实际值没有变化。
I know when we pass a parameter to the function a copy is created in the function's stack and there is no change in the actual value of the parameter in the caller's function.
当你传递一个函数指针会发生什么?我知道这个参数的值确实获取了来电者的功能改变。但它是如何在内部发生的呢?如何调用的函数中调用者的函数访问的变量?
What happens when you pass a pointer to the function? I know the value of the parameter does get changed in the callers function. But how does it happen internally? How does the called function access a variable in the caller's function?
我试图让从 Call_by_reference页面信息wikipeidia 但没有实质性的。
I tried to get information from Call_by_reference page in wikipeidia but was not substantial.
我很困惑这个,一旦我开始阅读有关字符串和传递字符串作为参数传递给其它功能。任何有关这帮助将是巨大的帮助。谢谢!!!!
I am confused with this once I started to read about strings and passing strings as parameters to other functions. Any help regarding this would be great help. Thanks!!!!
推荐答案
当你传递一个指向函数的指针,该指针被复制。然而,指针的一个拷贝到对象 X
也是一个指针 X
,所以它可用于修改 X
。
When you pass a pointer to a function, the pointer gets copied. However, a copy of a pointer to an object x
is also a pointer to x
, so it can be used to modify x
.
对于(做作)的比喻,假设 X
是你的房子。采用C的规则,当你需要一个管道工来修复你家的东西,你可以通过水暖工你的房子的副本,让他们解决这个问题,并给该副本还给你。不用说,对于房屋超过几个字节的,这是由于所有的复制相当低效的。因此,不是,你给管道工的指针的你的房子(其地址),使水管工可以访问你的房子和修复现场。这就是调用 - 引用是:你通过不是你想要修改的数据,而是一个指向数据,从而使被叫方知道的在哪个位置的,而不是只操作的上的值的
For a (contrived) analogy, suppose that x
is your house. By the rules of C, when you need a plumber to fix something in your house, you can either pass the plumber a copy of your house, have them fix that, and give the copy back to you. Needless to say, for houses larger than a few bytes, that's quite inefficient due to all the copying. So instead, you give the plumber a pointer to your house (its address), so that the plumber can access your house and fix it on the spot. That's what call-by-reference is: you pass not the data you want modified, but a pointer to that data, so that the callee knows at which location to operate instead of only on which value.
const int broken = 0, fixed = 1;
struct House {
int plumbing;
};
void plumber(House *h)
{
h->plumbing = fixed;
}
int main()
{
struct House h;
h.plumbing = broken;
plumber(&h); // give the plumber the address of the house,
// not a copy of the house
assert(h.plumbing == fixed);
}
在传递字符串的情况下,你传递的是一个指向第一个字符
中的字符串中。随着指针的算术运算,就可以得到下面的元素。
In the case of passing strings, what you pass is a pointer to the first char
in the string. With pointer arithmetic, you can then get to the following elements.
这篇关于用C按引用传递过程中会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!