确定。这可能是一个愚蠢的问题。
我正在尝试使用指针交换两个字符变量。以下是我的代码。
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指向的值相同。
我在这里做错了什么
答案 0 :(得分:3)
您应该存储x
指向tmp
的值,而不是地址x
本身(这意味着tmp
应该是char
)。
由于您tmp
设置为x
,因此您的代码基本上等同于:
*x = *y;
*y = *x;
答案 1 :(得分:1)
tmp
和x
指向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
}