DEV Community

Discussion on: Passing by value, passing by reference in C

Collapse
 
skillian profile image
Sean Killian

C passes arrays by reference: cplayground.com/?p=cassowary-aardv...

Collapse
 
dwimpy profile image
Dwimpy • Edited

That is incorrect. Arrays are contiguous blocks of memory and the only reason that works is because it is equivalent as passing int *array as a function argument and you are not trying to modify the actual array but the values inside the array.
You are passing a copy of the array which points to the first integer of the memory block.
When you are doing arr[2] you are dereferencing the memory address starting at 0x102 and changing its value. That is not passing by reference because if it were you would be able to modify the size of the array inside the function but that will not work.
cplayground.com/?p=boar-snake-manatee

Collapse
 
skillian profile image
Sean Killian

This is exactly the point I was attempting to make:

Arrays are contiguous blocks of memory and the only reason that works is because it is equivalent as passing int *array as a function argument

When I pass anything that is not an array to a function in C, the called function gets a copy of the passed value (i.e. "passed by value"). Changing the value does not affect the calling function's copy of the value. When I pass an array, the called function gets a pointer to the head of the array (i.e. "passed by reference"). The array behaves like a pointer even though its address was not explicitly passed.

cplayground.com/?p=quokka-hawk-lap...