Zuzu Zuzu - 4 years ago 102
C Question

Pass an array to a function by value

Below is a snippet from the book C Programming Just the FAQs. Isn't this wrong as Arrays can never be passed by reference?


VIII.6: How can you pass an array to a function by value?

Answer: An array can be passed to a function by value by declaring in
the called function the array name
with square brackets (
[
and
]
)
attached to the end. When calling the
function, simply pass the address of
the array (that is, the array’s name)
to the called function. For instance,
the following program passes the array
x[]
to the function named
byval_func()
by value:

The
int[]
parameter tells the
compiler that the
byval_func()

function will take one argument—an
array of integers. When the
byval_func()
function is called, you
pass the address of the array to
byval_func()
:

byval_func(x);


Because the array is being passed by
value, an exact copy of the array is
made and placed on the stack. The
called function then receives this
copy of the array and can print it.
Because the array passed to
byval_func()
is a copy of the
original array, modifying the array
within the
byval_func()
function has
no effect on the original array.

Answer Source

Because the array is being passed by value, an exact copy of the array is made and placed on the stack.

This is incorrect: the array itself is not being copied, only a copy of the pointer to its address is passed to the callee (placed on the stack). (Regardless of whether you declare the parameter as int[] or int*, it decays into a pointer.) This allows you to modify the contents of the array from within the called function. Thus, this

Because the array passed to byval_func() is a copy of the original array, modifying the array within the byval_func() function has no effect on the original array.

is plain wrong (kudos to @Jonathan Leffler for his comment below). However, reassigning the pointer inside the function will not change the pointer to the original array outside the function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download