Why do these swap functions behave differently?

前端 未结 5 906
抹茶落季
抹茶落季 2020-12-21 12:11
#include 

void swap1(int a, int b)
{
    int temp = a;

    a = b;
    b = temp;
}

void swap2(int *a, int *b)
{
    int *temp = a;

    a = b;
    b         


        
5条回答
  •  无人及你
    2020-12-21 12:22

    You're swap2 function has no effect.

    You are passing in two pointers. Inside the function, the (parameter) variables a and b are local to the function. The swap2 function just swaps the values of these local variables around - having no effect outside the function itself.

    As Anon pointed out, swap1 has the same problem - you're just modifying local variables.

提交回复
热议问题