简体   繁体   中英

How to swapping two variables with a pointer

I have a problem, I can't create a simple program for swapping two variables with a pointer. I tried in this way:

int main() {

int x=5, y=10;
int *p=nullptr;

p=&x;
y=*p;
x=y;

cout<<x<<" "<<y;
}

How can I do?

void swap(int *x, int *y)
{
    int tmp;

    tmp = *x;
    *x = *y;
    *y = tmp;
}
int main()
{
    int a = 7, b = 3;

    std::cout << a << ' ' << b << '\n';
    swap(&a, &b);
    std::cout << a << ' ' << b << '\n';
}

Also consider std::swap

The problem is that you are overwriting the original value of y with the value of x , then copying that value back to x .

What you want to do is to stash the value of x , copy the value of y to it, then move the stashed value to y .

Since you are trying to do this with pointers, you should probably change the operation x=y to use pointers as well. Here is an example:

int main(int argc, char *argv[])
{
    int x=5, y=10, stash;
    int *px, *py;

    cout << "Before: x=" << x << " y=" << y;

    px = &x;
    py = &y;

    stash = *px;
    *px = *py;
    *py = stash;

    cout << "After: x=" << x << " y=" << y;
}

Here's another good old way of swapping values of two variables without using a third variable:

x = x + y;  // x now becomes 15
y = x - y;  // y becomes 10
x = x - y;  // x becomes 5

Yet another way of doing it, as already pointed out by someone is using xor .

x = x ^ y;  // x now becomes 15 (1111)
y = x ^ y;  // y becomes 10 (1010)
x = x ^ y;  // x becomes 5 (0101)

There is also a one liner way of doing it:

x = x + y - (y = x);

You don't necessarily need pointers.

Limitation - As all the commentators have indicated, there is a limitation with all these approaches. These approaches may give you incorrect results if the sum of x and y exceeds INT_MAX (which may be equal to 2,147,483,647 on positive side and -2,147,483,648 on a negative side on a 32 bit system) AND your C implementation doesn't wrap around signed integers. However for your program, if you are working with relatively smaller numbers or your C implementation wraps around signed integers too, you should not have any issues using any of these 3 methods. But if you think that the sum might exceed INT_MAX , you can use the old fashioned temp variable approach to swap the values or use the standard swap function provided in the libraries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM