c++ - 交换指针

标签 c++ c pointers

<分区>

Possible Duplicate:
Swapping objects using pointers

我知道如何使用指针进行交换,但是,如果我尝试这样的不同方法:

/* Pointers */
#include <stdio.h>
int main ()
{
  int a=4,b=6;
  swap(&a,&b);
  printf("A is %d, and B is %d\n",a,b);
  return 0;
}

int swap(int *a, int *b)
{
  int *temp;
  temp = a;
  a = b;
  b = temp;
  return 0;
}

这是行不通的。基本上交换函数正在改变地址,比如'a'现在有'b'的地址,反之亦然。如果我打印出交换函数中的值,它会给出交换值,但它不会反射(reflect)在主要功能。谁能告诉我为什么?

最佳答案

因为

the swap function is changing the address, like 'a' now has the address of 'b', and vice-versa

不是真的。它不会改变他们的地址(这绝对没有任何意义)。该函数更改了指针的值 - 这些指针是地址的拷贝,并且这些指针是函数参数,因此对于函数而言是局部的。你要做的是:

int swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
    return 0;
}

或者您可以使用引用(仅在 C++ 中),如下所示:

int swap(int &a, int &b)
{
    int temp;
    temp = a;
    a = b;
    b = temp;
    return 0;
}

并在不带 addressof 运算符的情况下调用它:

int a = 4, b = 6;
swap(a, b);

但是,如果这是针对实际实现的,而不是“编写交换函数”式的作业,那么您应该使用 std::swap() function来自 <algorithm> .

关于c++ - 交换指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14180365/

相关文章:

c - c 中的声明错误

c++ - vector 声明

c++ - 如何深拷贝链表对象指针

c++ - 错误 openSSL 似乎缺乏椭圆曲线加密?这是什么意思以及如何解决?

c - 开发 C++ 与 OpenCV 崩溃

c - 对于已连接的非阻塞套接字,write 总是在一段时间后返回 EAGAIN

c - 使用C中的双指针将二维数组放入现有内存中

c++ - 'using'覆盖纯虚函数一个单独继承的方法

c++ - std::map<struct, int> 我需要析构函数吗?

C - 从函数获取正确的指针并通过另一个函数打印