C++ 使用指针交换字符变量

C++ 使用指针交换字符变量,c++,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; */ } 函数调用是-- 交换后,x和y指向的值与y指向的值相同 我在这里做错了什么您应该存储x指向tmp的值,而不是地址x本身(这意味着tmp应该是cha

嗯。这可能是个愚蠢的问题

我正在尝试使用指针交换两个字符变量

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

}
函数调用是--

交换后,x和y指向的值与y指向的值相同


我在这里做错了什么

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

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

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

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

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

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

tmp
x
char*tmp=x
之后指向同一位置,因此当您编写

*x = *y;
*tmp
也发生了变化。意味着随后的

*y = *tmp;
这是禁止的


使用
std::swap

tmp
x
指向
char*tmp=x
后的同一位置,因此在编写

*x = *y;
*tmp
也发生了变化。意味着随后的

*y = *tmp;
这是禁止的


使用
std::swap
我将根据您的原始代码进行更改,以便您看到错误。您应该做的是将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
}

我将根据您的原始代码进行更改,以便您看到错误。您应该做的是将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
}

你有什么特别的理由使用指针吗?无论如何,您需要一个临时变量,可以将要交换的两个值之一存储到其中。因为你的代码只涉及指针,所以你没有指针。你有什么特别的理由使用指针吗?无论如何,您需要一个临时变量,可以将要交换的两个值之一存储到其中。因为您的代码只涉及指针,所以您没有指针。