Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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!!!!

like image 749
Shash Avatar asked Oct 18 '12 11:10

Shash


Video Answer


1 Answers

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.

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.

like image 145
Fred Foo Avatar answered Nov 02 '22 22:11

Fred Foo