1 c
这段代码基本上应该是一个字符串,比如说它是“abc de fgh”,输出应该是
cba
ed
hgf
Run Code Online (Sandbox Code Playgroud)
此处显示的代码确实将字符串放入一行中,但不会反转它们。我在想出那部分以及如何在方法中使用我的参数中的 char* 时遇到了麻烦。任何在正确方向上的帮助都会很棒!
void stringReverse(char* s){
char* i = 0;
char* j = strlen(s)-1;
//in order to swap the characters s[i] and s[j] make a temp
char* temp;
while(i < j){
temp = i;
i = j;
j = temp;
i++;
j--;
}
//end of the while loop means that it reversed everything (no need for if/else)
}
Run Code Online (Sandbox Code Playgroud)
您的代码似乎混合了使用索引(如0或strlen(s)-1)或使用指针的概念。即使在评论中您写了“交换字符s[i]和s[j]”,但您将i和声明j为char*变量。
第二个错误是您交换了指针值,而不是指针指向的字符。
您应该决定是使用指针还是索引来访问字符。
使用指针的解决方案:
void stringReverse(char* s){
//in order to swap the characters s[i] and s[j] make a temp
char temp;
char* i = s;
/* according to the standard, the behavior is undefined if the result
* would be one before the first array element, so we cannot rely on
* char* j = s + strlen(s) - 1;
* to work correct. */
char* j = s + strlen(s);
if(j > i) j--; // subtract only if defined by the C standard.
while(i < j){
temp = *i;
*i = *j;
*j = temp;
i++;
j--;
}
//end of the while loop means that it reversed everything (no need for if/else)
}
Run Code Online (Sandbox Code Playgroud)
使用索引的解决方案:
void stringReverse(char* s){
size_t i = 0;
size_t j = strlen(s)-1;
//in order to swap the characters s[i] and s[j] make a temp
char temp;
while(i < j){
temp = s[i];
s[i] = s[j];
s[j] = temp;
i++;
j--;
}
//end of the while loop means that it reversed everything (no need for if/else)
}
Run Code Online (Sandbox Code Playgroud)
如果启用了足够多的警告,编译器应该警告原始源代码中的一些问题。我建议始终启用尽可能多的警告。