[英]Program printing wrong output
Why is the following code printing !notreblo!
为什么下面的代码打印!notreblo!
instead of !notrebloH
?而不是!notrebloH
? Where is the !
在哪里!
coming from?来自(哪里? I am trying to write a program that reverses an array and I am using the main
function to test the rev_string
function.我正在尝试编写一个反转数组的程序,我正在使用main
函数来测试rev_string
函数。
#include <stdio.h>
int main(void)
{
char s[11] = "Holberton!";
printf("%s\n", s);
rev_string(s);
printf("%s\n", s);
return (0);
}
void rev_string(char *s)
{
char new[500];
int count, newcount;
count = 0, newcount = 0;
while (*(s + count) != '\0')
{
*(new + count) = *(s + count);
count++;
}
count--;
while (count > 0)
{
*(s + newcount) = *(new + count);
count--;
newcount++;
}
}
The second while
does not copy the first character, because the last character copied is at index 1. The condition tells it so: count > 0
.第二个while
不复制第一个字符,因为复制的最后一个字符位于索引 1 处。条件告诉它: count > 0
。
Change it to count >= 0
.将其更改为count >= 0
。
(+1 for the famous "one-off" error. If I got 1 cent each time, I'll be a rich person.) (对于著名的“一次性”错误+1。如果我每次得到 1 美分,我就会成为一个富人。)
Notice your second while
condition: while (count > 0)
.注意你的第二个while
条件: while (count > 0)
。 You aren't including your last character - eg if count == 3
(3 characters to reverse), you will only iterate twice - and your third character will not be written.您不包括最后一个字符 - 例如,如果count == 3
(要反转 3 个字符),则您只会迭代两次 - 并且不会写入您的第三个字符。 You need to change the condition to while (count >= 0)
.您需要将条件更改为while (count >= 0)
。
As a bonus, the function you are implementing is better known as strrev - and it can be implemented without an additional buffer.作为奖励,您正在实现的功能更广为人知的是strrev - 它可以在没有额外缓冲区的情况下实现。
因为您应该将第二个 while 条件更改为while (count >= 0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.