I wrote a function containing array as argument, and call it by passing value of array as follows.
void arraytest(int a[]) { // changed the array a a[0] = a[0] + a[1]; a[1] = a[0] - a[1]; a[0] = a[0] - a[1]; } void main() { int arr[] = {1, 2}; printf("%d \t %d", arr[0], arr[1]); arraytest(arr); printf("\n After calling fun arr contains: %d\t %d", arr[0], arr[1]); }
What I found is though I am calling arraytest()
function by passing values, the original copy of int arr[]
is changed.
Can you please explain why?
Single array elements can also be passed as arguments. This can be done in exactly the same way as we pass variables to a function.
In case, when an array (variable) is passed as a function argument, it passes the base address of the array. The base address is the location of the first element of the array in the memory.
When passing an array as a parameter, this
void arraytest(int a[])
means exactly the same as
void arraytest(int *a)
so you are modifying the values in main.
For historical reasons, arrays are not first class citizens and cannot be passed by value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With