0

passing array example Hi, I have problem understanding the concept of 'passing an array by reference instead of value' and I cant understand this example. Can anyone explain to me why does it take 10, 22 as final answer?

2

When the code calls set_int(a), the value stored in x in main(), 10, is passed to set_int(). That "10" is a copy of the original and is stored in a local variable, x, inside of set_int(). Then, x is changed to 22 inside of set_int(). The important thing to remember here is this: The variable in main that held "10" will not be changed by anything in set_int(). Only the copy stored in set_int(). So, when x is changed to 22 in set_int(), nothing in main(), including a will be changed. When set_int() ends and control returns to main(), every variable in set_int() ceases to exist.

Now, the array is a slightly different story. Just like before, variables are passed by copy. But in this case, when main() calls set_array(b), it is passing a copy of the address of the array or the array location to set_array(). Even though it's a copy of the address that is passed, any use or reference to that address will point back to the same memory that is used by main(). So, when the code executes array[0] = 22; the integer stored in the first or 0th position in the array will be changed, and that change will still be there when the code finishes the function call and returns to main.

So, that's all there is to it. Any questions?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thank you so much! – xxtan1 Aug 17 '20 at 7:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .