c - 为什么使用输入字符串在屏幕上打印垃圾值?
问题描述
我试图在 c 中使用动态内存分配创建字符串类型数据类型。
我的代码正在打印用户输入的字符,但它也在下一行打印一些垃圾值。为什么会这样?
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
int n = 1, i = 0;
char a = 0;
char *str = NULL;
str = malloc(sizeof(char) * (n));
printf("Enter string : ");
while (a != '\n')
{
a = getchar();
str = realloc(str, sizeof(char) * (n));
str[i++] = a;
n++;
}
printf(str);
free(str);
}
输入:
"q"
输出:
q
"garbage value"
解决方案
这是您的程序,改动很小:
#include <stdio.h>
#include <stdlib.h>
void main(void)
{
int n = 1, i = 0;
char a = 0;
char *str = NULL;
str = malloc(sizeof(char) * (n+1)); // reserve space for a zero byte
printf("Enter string : ");
while (a != '\n')
{
a = getchar();
str = realloc(str, sizeof(char) * (n+1)); // reserve space for a zero byte
str[i++] = a;
str[i+1] = 0; // add a zero byte
n++;
}
puts(str); // puts instead of printf
free(str);
}
推荐阅读
- c# - C# WPF MVVM - 将多个 csv 合并到数据网格
- c - What is int (*fp)()
- javascript - 如何在没有控制器的情况下访问视图中的 dataModel
- python - 如何抑制py.test单字符测试结果输出?
- angular - 应该存在的功能未定义?
- mysql - utf-8 charset txt 文件转换为 mysql 无法在 macos 上正确显示
- r - 在 R 中添加两个核密度对象?
- python - Python ftplib:以写入模式打开文件?
- excel - 后期绑定 Microsoft Windows 公共控件 (TreeView) 对象
- azure-active-directory - Azure AD B2C 中的按钮输入类型