在C ++中交换指针的地址 [英] Swapping addresses of pointers in C++

查看:191
本文介绍了在C ++中交换指针的地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在签名函数中交换指针地址?

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

我们假设:

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

因此,在退出此函数后,实际参数的地址( weight height )。是否可能?

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

推荐答案

如果你想交换指针指向的地址,而不仅仅是存储的值在该地址,您需要通过引用(或指向指针的指针)传递指针。

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
}

或者可以使用STL交换函数并传递指针。

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.

这篇关于在C ++中交换指针的地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆