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?

3

11 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.

5

For passing 2D (or higher multidimensional) arrays instead, see my other answer here: How to pass a multidimensional array to a function in C and C++

Passing 1D arrays as function parameters in C (and C++)

Marcus Vance

Marcus Vance

Cybersecurity & Digital Privacy Researcher

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.