【问题标题】:why code printing garbage value on screen with input string? [duplicate]为什么使用输入字符串在屏幕上打印垃圾值? [复制]
【发布时间】: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


【解决方案1】:

这是您的程序,改动很小:

#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);
}    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-17
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2019-05-09
    • 2021-12-22
    • 2018-02-18
    • 1970-01-01
    相关资源
    最近更新 更多