Swapping variables with a function doesn't affect the call site

前端 未结 2 925
我在风中等你
我在风中等你 2021-01-23 07:29

A few lessons ago I learned about variables, and got a question in my homework about swapping two numbers - I used a third variable to solve this question.

The solution

相关标签:
2条回答
  • 2021-01-23 07:39

    What you are doing is passing parameter by value. It means that during the function call, copies of parameters are created. So inside the function you are working on copies of actual variables.

    Instead you need to pass it as a reference. Please read more about pass-by-value vs pass-by-reference.

    #include <stdio.h>
    void swap(int& x,int& y)    //Instead of passing by value just pass by reference
    {
        int temp=x;
        x=y;
        t=yemp;
    }
    int main() {
        int a=3,b=4;
        swap(a,b);
        printf("%d %d\n",a,b);
    
        return 0;
    }
    

    EDIT: C does not have references. Above code will work in c++ instead. To make in work in C, just use pointers and de-reference it inside the function.

    0 讨论(0)
  • 2021-01-23 07:50

    Pass address of x and y as arguments to function. Right now they are local variables, changes are not made to original variables .

    Do as follows-

    void swap(int *x,int *y){
     /*            dereference pointers and  swap    */
     int temp = *x;
     *x = *y;
     *y = temp;
    }
    

    And call in main like this -

    swap(&x,&y);
    
    0 讨论(0)
提交回复
热议问题