Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array as an argument to a function in C

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?

like image 820
Mohan Mahajan Avatar asked Jul 04 '11 05:07

Mohan Mahajan


People also ask

Can an array be used as an argument to a function?

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.

When an array is passed as an argument 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.


1 Answers

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.

like image 184
Bo Persson Avatar answered Sep 29 '22 08:09

Bo Persson