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!!!!
When you pass a pointer to a function, the pointer gets copied. However, a copy of a pointer to an object
xis also a pointer tox, so it can be used to modifyx.For a (contrived) analogy, suppose that
xis 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.In the case of passing strings, what you pass is a pointer to the first
charin the string. With pointer arithmetic, you can then get to the following elements.