简体   繁体   中英

why results of these two functions are different?

I expected results are same. Two functions do same thing but
why they are different?
I think its related to pointers.

void changer(int n){
    n = 20;
}

void arrayChanger(int n[]){
    n[0] = 20;
}

int main()
{
    int a = 5;
    int ar[1] = {5};

    changer(a);
    arrayChanger(ar);

    printf("%d\n",a);
    printf("%d\n",ar[0]);

    return 0;
}

Arguments are passed by value unless the argument is specifically declared to be passed by reference , and arrays will decay to a pointer to their first element when passed to functions.

The function changer does not update the actual variable a since it only receives its value, not the variable itself.

If you want to update a value in a function call, you need to pass it by reference:

void make20(int *a) 
{
    *a = 20;
}

The call would then look like:

int n = 5;
make20(&n);
// now n = 20

In changer(a) , you pass an int as the parameter. This int is passed by value. That means that when changer executes, it simply receives the int 5 as a parameter and sets the parameter to 20. However, since the parameter is passed by value, there is no change to the parameter outside of the function.

In arrayChanger(ar) , you pass an array as the parameter. As mentioned by Osiris, when passing an array to a function, it 'decays' to a pointer to the first element of said array. Therefore, in arrayChanger , you set the value at the pointer to 20. This means that after execution, the value at the pointer (which has remained constant) is now 20 rather than the original 5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM