Swapping addresses of pointers in C++

后端 未结 5 2049
温柔的废话
温柔的废话 2021-01-01 02:38

How can one swap pointer addresses within a function with a signature?

Let\'s say:

int weight, height;
void swap(int* a, int* b);

S

5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-01 03:00

    If you want to swap the addresses that the pointers are pointing to, not just the values stored at that address, you'll need to pass the pointers by reference (or pointer to pointer).

    #include 
    void swap(int*& a, int*& b)
    {
        int* c = a;
        a = b;
        b = c;
    }
    
    int main()
    {
        int a, b;
        int* pa = &a;
        int* pb = &b;
    
        swap(pa, pb);
    
        assert(pa == &b);  //pa now stores the address of b
        assert(pb == &a);  //pb now stores the address of a
    }
    

    Or you can use the STL swap function and pass it the pointers.

    #include 
    
    std::swap(pa, pb);
    

    Your question doesn't seem very clear, though.

提交回复
热议问题