我正在尝试找出 K&R 的练习 1.19。
Write a function reverse(s) that reverses the characte string s. Use it to write a program that reverses its input a line at a time
这是我的代码
#include <stdlib.h>
#include <stdio.h>
#define MAX 150
void reverse(char s[]);
int main()
{
int c, i;
char string[MAX];
i=0;
while((c=getchar())!= EOF){
while((c=getchar()) != '\n'){
string[i] = c;
i++;
}
reverse(string);
}
return 0;
}
void reverse(char s[]){
int i, j;
for(i=0; i<MAX-1; i++){
if(s[i] == '\n')
break;
}
for(j=i;j>=0;j--)
printf("%c", s[j]);
printf("\n");
}
我试图弄清楚,但对我来说没有意义。 预先感谢您的帮助。
最佳答案
您的代码中有几个问题。
首先,您通过 EOF 检查“吞掉”第一个字符;第一个写入数组的实际上是第二个(如果您输入 string^ 它会将
tring` 复制到缓冲区)。
然后,无论包含的字符串长度如何,都将反转整个缓冲区(150 个字符)。您看到的垃圾只是您也反转的缓冲区的“其余部分”。请注意,“垃圾”的最后一个字符是 gnirt
,它是 tring
反转的。
然后还要注意正确的字符串终止符 \0
。
关于c - 未定义的输出(K&R 1.19),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36694843/