C++ Swapping Pointers

后端 未结 5 1293
天涯浪人
天涯浪人 2020-12-05 11:21

I\'m working on a function to swap pointers and I can\'t figure out why this isn\'t working. When I print out r and s in the swap function the values are swapped, which lea

5条回答
  •  孤城傲影
    2020-12-05 12:12

    The line r=s is setting a copy of the pointer r to the copy of the pointer s.

    Instead (if you do not want to use the std:swap) you need to do this

    void swap(int *r, int *s)
    {
        int tmp = *r;
        *r = *s;
        *s = tmp;
    }
    

提交回复
热议问题