首页 > 解决方案 > 为什么使用输入字符串在屏幕上打印垃圾值?

问题描述

我试图在 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"

标签: 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+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);
}    

推荐阅读