Unable to change values in a function

后端 未结 3 916
逝去的感伤
逝去的感伤 2021-01-20 23:59

I\'m starting with developing, sorry about this newbie question.

I need to create a function that swap values between 2 vars.

I have wrote this code, but no chan

3条回答
  •  失恋的感觉
    2021-01-21 00:15

    you are passing by value. you can still pass by value but need to work with pointers.

    here is the correct code needed:

    void swap(int *i, int *j) {
       int t = *i;
       *i = *j;
       *j = t;
    }
    
    void main() {
       int a = 23, b = 47;
       printf("Before. a: %d, b: %d\n", a, b);
       swap(&a, &b);
       printf("After . a: %d, b: %d\n", a, b);
    }
    

    also a small document that explains "by reference" vs "by value" : http://www.tech-recipes.com/rx/1232/c-pointers-pass-by-value-pass-by-reference/

提交回复
热议问题