我真的不明白为什么在第一种情况下代码不起作用而在第二种情况下代码工作正常。第一种情况和第二种情况之间的区别在于,在第一种情况下,我在一行中编写了交换算法,在第二种情况下,我在几种情况下编写了相同的交换算法。
编译请运行:g ++ -DDEBUG -o str_reverce str_reverce.cpp
抱歉我的英文。
第一种情况:
#include <iostream>
using namespace std;
#ifdef DEBUG
#define debug(arg) cout << __FUNCTION__ << ":" << __LINE__ << ": " << arg << endl;
#else
#define debug(arg)
#endif
char *str_reverse(char *str)
{
if (str == NULL) {
debug("wrong arg!");
return NULL;
}
debug("before: " << str);
unsigned int i = 0, j = 0;
while (str[i] != '\0') // Find out string length
++i;
debug("string length: " << i);
if (i <= 1) {
debug("string is too small!");
return str;
}
// a = b^(b^a)
// b = a^(b^a)
for (j = 0; j < i/2; j++) {
/*str[i-j-1]=str[i-j-1]^str[j];
str[j]=str[j]^str[i-j-1];
str[i-j-1] = str[i-j-1]^str[j];*/
str[i-j-1] = str[i-j-1]^(str[j]=str[j]^(str[i-j-1]=str[i-j-1]^str[j]));
}
debug("after: " << str);
return str;
}
int main(int argc, char *argv[])
{
char str[] = "0123456789";
str_reverse(str);
}
第二种情况:
#include <iostream>
using namespace std;
#ifdef DEBUG
#define debug(arg) cout << __FUNCTION__ << ":" << __LINE__ << ": " << arg << endl;
#else
#define debug(arg)
#endif
char *str_reverse(char *str)
{
if (str == NULL) {
debug("wrong arg!");
return NULL;
}
debug("before: " << str);
unsigned int i = 0, j = 0;
while (str[i] != '\0') // Find out string length
++i;
debug("string length: " << i);
if (i <= 1) {
debug("string is too small!");
return str;
}
// a = b^(b^a)
// b = a^(b^a)
for (j = 0; j < i/2; j++) {
str[i-j-1]=str[i-j-1]^str[j];
str[j]=str[j]^str[i-j-1];
str[i-j-1] = str[i-j-1]^str[j];
//str[i-j-1] = str[i-j-1]^(str[j]=str[j]^(str[i-j-1]=str[i-j-1]^str[j]));
}
debug("after: " << str);
return str;
}
int main(int argc, char *argv[])
{
char str[] = "0123456789";
str_reverse(str);
}
谢谢!