我有一个练习来编写一个替换没有第三个变量的值的函数,我尝试了一些解决方案,但没有得到它们。
我写了以下代码:
void swap1(int* p1, int* p2) {
p1++;
*p1 = *p2;
p1--;
*p2 = *p1;
p1++;
cout << *p1 << endl;
}
主要:
int main() {
int n1 = 5, n2 = 8;
cout << "before swap: " << endl;
cout << "value 1: " << n1 << " value 2: " << n2 << endl;
swap1(&n1, &n2);
cout << "after swap: " << endl;
cout << "value 1: " << n1 << " value 2: " << n2 << endl;
return 0;
}
我得到以下输出:
before swap:
value 1: 5 value 2: 8
8
after swap:
value 1: 5 value 2: 5
Press any key to continue . . .
为什么当我在我的函数中打印时,这实际上交换了值,但在main
中没有?
怎么了?
*p1 = p1++;
&gt;&gt;为什么不工作? (我在理论上尝试做的事)
答案 0 :(得分:4)
没有溢出。
请参阅http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/
int main() {
int n1 = 5, n2 = 8;
cout << "before swap: " << endl;
cout << "value 1: " << n1 << " value 2: " << n2 << endl;
n2 = n1^n2;
n1 = n1^n2;
n2 = n1^n2;
cout << "after swap: " << endl;
cout << "value 1: " << n1 << " value 2: " << n2 << endl;
return 0;
}
答案 1 :(得分:1)
正如之前的答案中所建议的那样......只需按照您提议的形式输入:
void swap2(int* p1, int* p2) {
if(p1 != p2) {
*p2 = (*p1)^(*p2);
*p1 = (*p1)^(*p2);
*p2 = (*p1)^(*p2);
}
}
答案 2 :(得分:-1)
int main() {
int n1 = 5, n2 = 8;
cout << "before swap: " << endl;
cout << "value 1: " << n1 << " value 2: " << n2 << endl;
n2 = n1+n2;
n1 = n2 -n1;
n2 = n2-n1;
cout << "after swap: " << endl;
cout << "value 1: " << n1 << " value 2: " << n2 << endl;
return 0;
}