[英]Why does my reverse function not work in C?
void str_reverse(char *l, char *r){
char *start = l; //gives while loop place to stop, the start of the string
while (*l != '\0'){
*l++;
} //loops the to the end terminator
*l--; //last character
while (*l != *start){
*r = *l;
*l--;
*r++;
} // adds the string from back to front to new string
*r = '\0';
}
当我打印出* r时,有人可以告诉我,为什么我错过了第一个字符? 例如,你好,是奥勒吗? 谢谢
错误是使用* l ++之类的具有取消引用的指针来递增指针,并将指针与它们所指向的值进行比较。 固定代码如下所示:
void str_reverse(char *l, char *r){
char *start = l; //gives while loop place to stop, the start of the string
while (*l != '\0'){
l++;
} //loops the to the end terminator
l--; //last character
while (l >= start){
*r = *l;
l--;
r++;
} // adds the string from back to front to new string
*r = '\0';
}
更改为做时:
do {
*r = *l;
l--;
r++;
// adds the string from back to front to new string
} while (l != start);
*r = '\0';
很少有支票是错误的。 首先while(*l != *start)
循环将退出而不复制最后一个字符。
因此,支票应基于地址。
while(l >= start)
只是您需要递增和递减指针*l--
和*r++
并非您打算这样做。
#include <stdio.h>
#include <string.h>
void str_reverse(char *l, char *r){
char *start = l; //gives while loop place to stop, the start of the string
while (*l != '\0'){
*l++;
} //loops the to the end terminator
*l--; //last character
while (l >= start){
*r = *l;
l--;
r++;
} // adds the string from back to front to new string
*r = '\0';
}
int main()
{
char a[20] = "somestring";
char b[20];
str_reverse(a,b);
printf("%s",b);
return 0;
}
void str_reverse(char *l, char *r) {
char *start = l; //gives while loop place to stop, the start of the string
while (*l != '\0'){
l++;
} //loops the to the end terminator
l--; //skips \0
while (l >= start){
*r = *l;
l--;
r++;
} // adds the string from back to front to new string
*r = '\0';
}
请注意,while条件已更改,并且指针算法正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.