Array changes it's values inside a function but other variable don't

#include <iostream>

using std::cout;
using std::cin;
using std::endl;

void func(int arr[5], int n1, int n2)
{   
    cout << "INSIDE func()" << endl;
    arr[0]++, arr[3]++;
    for(int i = 0; i < 5; i++)
    {
        cout << arr[i] << ' ';
    }
    cout << endl;
    n1++, n2++;
    cout << n1 << ' ' << n2 << endl;
}

int main()
{
    int a = 3, b = 4;
    int arr[5] = {0,0,0,0,0};
    
    func(arr,a,b);
    cout << "INSIDE main()" << endl;
    for(int i = 0; i < 5; i++)
    {
        cout << arr[i] << ' ';
    }
    cout << endl;
    cout << a << ' ' << b << endl;

    return(0);
}

So, why does arr[5] changes it’s values in func() function, but variables a,b don’t.
Why does that happen? I know that to a,b change it’s values i have to pass the reference of variables a , b to function func().

F.e:
fill(int arr[5], int &n1, int &n2)
{
   /* code */
}

But why don’t we pass arrays to functions in the same way?

OUTPUT:

INSIDE func()
1 0 0 1 0
4 5
INSIDE main()
1 0 0 1 0
3 4

>Solution :

This function declaration

void func(int arr[5], int n1, int n2);

is adjusted by the compiler to the declaration

void func(int *arr, int n1, int n2);

That is parameters having array types are adjusted by the compiler to pointers to array element types.

On the other hand, this call

 func(arr,a,b);

is equivalent to the call

 func( &arr[0], a, b );

That is the array designator arr used as the function argument is implicitly converted to a pointer to its first element.

So in fact elements of the array are passed to the function through a pointer to them because using the pointer arithmetic and dereferencing pointer expressions the function has a direct access to elements of the array. For example these expressions

arr[0]++, arr[3]++;

by the definition are equivalent to

( *( arr + 0 ) )++, ( *( arr + 3 ) )++;

As for the variables a and b then the function deals with copies of the values of these variables. If you want to get the same effect as with elements of the array you should define the function like

void func(int arr[5], int *n1, int *n2)
{   
    cout << "INSIDE func()" << endl;
    arr[0]++, arr[3]++;
    for(int i = 0; i < 5; i++)
    {
        cout << arr[i] << ' ';
    }
    cout << endl;
    ( *n1 )++, ( *n2 )++;
    cout << *n1 << ' ' << *n2 << endl;
}

and call it like

 func( arr, &a, &b );

Leave a Reply