使用指针交换字符变量

时间:2015-01-11 14:39:45

标签: c++

确定。这可能是一个愚蠢的问题。

我正在尝试使用指针交换两个字符变量。以下是我的代码。

void swap_char(char* x, char* y)
{ 
char *tmp=x;
 *x=*y;
*y=*tmp;  

/* int t=*x;
 *x=*y;        // this works fine and i understand
*y=t;
*/

}

和函数调用是 -

swap_char(&s[0],&s[j]); // where s is std::string variable
x和y指向的

值与交换后y指向的值相同。

我在这里做错了什么

3 个答案:

答案 0 :(得分:3)

您应该存储x指向tmp的值,而不是地址x本身(这意味着tmp应该是char )。

由于您tmp设置为x,因此您的代码基本上等同于:

*x = *y;
*y = *x;

答案 1 :(得分:1)

tmpx指向char* tmp=x之后的同一位置,因此在您撰写时

*x = *y;

*tmp也发生了变化。意思是后续的

*y = *tmp;

是无操作。

使用std::swap

答案 2 :(得分:1)

我会根据原始代码进行更改 - 以便您看到错误。你应该做的是分配"值" x到tmp - 而不是指针本身。后者是你的tmp声明/初始化发生的事情。详细内联代码。

void swap_char(char* x, char* y)
{ 
//  char *tmp=x; // this would create a new tmp pointer and assign "tmp" with x - and NOT "*tmp" with *x".
    char tmp = *x; // new code - store the VALUE pointed by x in tmp
     *x=*y; // store VALUE pointed by y to storage pointed by x
    *y=tmp; // modified to delete * from tmp - store VALUE of tmp to storage pointed by y
}