交换指针 [英] Swapping pointers

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

问题描述

可能重复:结果
  交换使用指针对象

我知道该怎么做使用指针交换,不过呢,如果我尝试了不同的方法是这样的:

I know how to do swapping using pointers, but then, if I try a different approach like this:

/* 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;
}

这是行不通的。基本上交换功能正在改变地址,像'一'现在有'B'的地址,反之亦然。如果我在交换功能打印出的价值观,它给交换价值,但它并没有反映在主功能。任何一个可以告诉我为什么?

It doesn't work. Basically the swap function is changing the address, like 'a' now has the address of 'b', and vice-versa.. If I print out the values in swap function, it gives swapped values, but it is not reflected in main function. Can any one tell me why?

推荐答案

由于

交换功能正在改变地址,像'一'现在有'B'的地址,反之亦然。

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

是不正确的。它并没有改变他们的地址(这将使绝对没有任何意义)。该函数改变指针的值 - 这些指针地址的副本,这些指针,因为他们是函数的参数,是局部的功能。你有什么要做的是:

is not true. It doesn't change their addresses (that would make absolutely no sense whatsoever). The function changes the values of the pointers - those pointers are copies of the addresses, and these pointers, since they're function arguments, are local to the function. What you have to do is:

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

或者你可以使用引用(仅在C ++),像这样的:

Or you can use references (only in C++), like this:

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

和调用它的没有 AddressOf运算符:

and call it without the addressof operator:

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

不过,如果这是一个实际的执行,而不是写一个交换功能式的功课,那么你应该使用的std ::互换()功能 &LT;算法方式&gt;

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

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