C ++交换指针 [英] C++ Swapping Pointers

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

问题描述

我正在处理一个函数来交换指针,我不知道为什么这不工作。当我在交换函数中打印出r和s时,值被交换,这使我相信我操作一个我不明白的副本,因为我通过参考p和q。

  void swap(int * r,int * s)
{
int * pSwap = r;
r = s;
s = pSwap;
return;
}

int main()
{
int p = 7;
int q = 9;
swap(& p,& q);
cout<< p =<< p < q =< q<< endl;
return 0;
}

列印:p = 7q = 9


<在你的 swap 函数里面,你只是改变指针的方向,即改变对象的指针指向(这里,具体来说,它是对象的地址 p q )。指针指向的对象根本不改变。



您可以直接使用 std :: swap 。或者编写你的交换函数,如下所示:

  void swap(int * r,int * s)
{
int temp = * r;
* r = * s;
* s = temp;
return;
}


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 leads me to believe I'm manipulating a copy of which I don't understand because I pass by reference of p and q.

void swap(int *r, int *s)
{
    int *pSwap = r;
    r = s;
    s = pSwap;
    return;
}

int main()
{
    int p = 7;
    int q = 9;  
    swap(&p, &q);
    cout << "p = " << p << "q= " << q << endl;
    return 0;
}

Prints: p = 7q = 9

解决方案

Inside your swap function, you are just changing the direction of pointers, i.e., change the objects the pointer points to (here, specifically it is the address of the objects p and q). the objects pointed by the pointer are not changed at all.

You can use std::swap directly. Or code your swap function like the following:

void swap(int *r, int *s)
{
   int temp = *r;
   *r = *s;
   *s = temp;
   return;
} 

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

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