C++ Swapping Pointers

后端 未结 5 1286
天涯浪人
天涯浪人 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条回答
  •  Happy的楠姐
    2020-12-05 12:09

    The accepted answer by taocp doesn't quite swap pointers either. The following is the correct way to swap pointers.

    void swap(int **r, int **s)
    {
        int *pSwap = *r;
        *r = *s;
        *s = pSwap;
    }
    
    int main()
    {
        int *p = new int(7);
        int *q = new int(9);
    
        cout << "p = " << std::hex << p << std::endl;
        cout << "q = " << std::hex << q << std::endl << std::endl;
    
        swap(&p, &q);
    
        cout << "p = " << std::hex << p << std::endl;
        cout << "q = " << std::hex << q << std::endl << std::endl;
    
        cout << "p = " << *p << " q= " << *q << endl;
        return 0;
    }
    

    Output on my machine:

    p = 0x2bf6440
    q = 0x2bf6460
    
    p = 0x2bf6460
    q = 0x2bf6440
    
    p = 9 q= 7
    

提交回复
热议问题