c - Why does my code print out some garbage from my array?
问题描述
I am currently learning C, and I want to create a function that reverses an input. Here is the piece of code I wrote:
#include <stdio.h>
int main(int argc, char** argv) {
char input[100];
while(1) {
fgets(input, 100, stdin);
for(int i = 99; i > -1; i--) {
printf("%c", input[i]);
}
printf("\n");
}
}
The output of this is correct, but it also prints some garbage in between and I don't understand why. Can someone explain this to me?
This is the output:
解决方案
Firstly, you should clear memory before using it.
Secondly, always keep one char with 'NULL' value at the end of a string. (only an option for your case, because you are not using sprintf
, strcpy
... and so on.)
Thirdly the for
loop should start at the end of the input, that is strlen(input)
which is located on <string.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv) {
char input[100];
while(1) {
memset(input, 0, sizeof(input)); // add memset() to clear memory before using it
fgets(input, 100, stdin);
for(int i = strlen(input); i > -1; i--) {
printf("%c", input[i]);
}
printf("\n");
}
}
推荐阅读
- c# - 使用 LINQ Query 加入两个列表并仅显示相关数据
- grails - 更新用户配置文件时,无需用户输入即可将权限分配给用户
- spring-boot - 我是响应式编程的新手,尝试使用 Mono 和 concat 进行 UPSERT 操作,并在存储库中存在值
- html - CSS-Grid 中的网格
- javascript - React 刷新重定向到主页,与刷新页面的 url 相同
- typescript - Angular Test Simple Component -> NullInjectorError: No provider for xxx
- javascript - 在 Kotlin 的 WebView 的 JavascriptInterface 中执行页面的 JavaScript
- android - 当我点击 TextField 然后键盘打开但 TextField 没有在顶部颤动 Android 上滑动
- javascript - jQuery 函数不运行以显示“模态”元素
- ios - 通过 iOS 中的配置文件手动安装后,自签名证书不起作用