【发布时间】:2019-04-12 18:43:11
【问题描述】:
我试图在 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"
【问题讨论】:
-
您需要通过在末尾放置一个 0 字节来终止字符串。
-
可能是空终止。
标签: c