Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swapping addresses of pointers in C++

Tags:

c++

pointers

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

Let's say:

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

So after going out of this function the addresses of the actual parameters (weight and height) would be changed. Is it possible at all?

like image 415
There is nothing we can do Avatar asked Dec 01 '09 13:12

There is nothing we can do


2 Answers

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 <cassert>
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 <algorithm>

std::swap(pa, pb);

Your question doesn't seem very clear, though.

like image 151
UncleBens Avatar answered Oct 05 '22 22:10

UncleBens


In C++ you would write

 void swap(int *a, int *b)
 {
    std::swap(*a, *b);
 }

or rather just use:

 std::swap(a, b);
like image 22
RED SOFT ADAIR Avatar answered Oct 05 '22 23:10

RED SOFT ADAIR