【问题标题】:Garbage characters are printed forcefully [duplicate]垃圾字符被强制打印[重复]
【发布时间】:2019-05-09 21:45:34
【问题描述】:

这是一个程序,它应该读取输入、一个数字“n”和一个字符,然后将该字符复制 n 次。它工作得很好,但是当我输入一个大数字时,例如 8+,它会完美复制,但会在末尾添加垃圾值。我不明白为什么会这样,因为我使用了 malloc 并且我在内存中正好为我保存了 n 个块。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* create_string (char ch, int n);
void main ()
{
    int n;
    char ch;
    printf("Enter number for duplicates: ");
    scanf("%d",&n);
    printf("Enter a letter: ");
    scanf(" %c", &ch);
    printf("The letter '%c' duplicated %d times is: ",ch,n);
    char* ptr=create_string(ch,n);
    printf("%s",ptr);
}
char* create_string (char ch, int n)
{
    char* dup=(char*)malloc(n*sizeof(char));
    int i;
    for (i=0; i<n; i++)
    {
        dup[i]=ch;
    }
    return dup;
}

试运行:

【问题讨论】:

  • 您的create_string 函数没有创建字符串。
  • 我看不到“试运行”图片。

标签: c string character


【解决方案1】:

C 中的字符串就像以空字符结尾的字符序列一样简单。这意味着每当您手动创建字符串时,您必须始终在末尾附加 '\0',以便其他函数(如 printf)知道它的结尾:

char* create_string (char ch, int n)
{
    char* dup = malloc((n+1) * sizeof(char));
    int i;
    for (i=0; i<n; i++)
    {
        dup[i]=ch;
    }

    // This is important
    dup[n] = '\0';

    return dup;
}

另一个需要注意的微妙之处是,因为您需要存储终止空字符,您还需要为它保留空间。所以malloc这一行变成了:

malloc((n+1)*sizeof(char))
//     ^^^^^ it's no longer 'n'

顺便说一句,您don't need to 转换了malloc 的返回指针。

【讨论】:

  • @KeineLust 看起来我错过了这一点。谢谢
  • 乘以sizeof (char) 是没有意义的。根据定义,它是 1。
  • @melpomene 保持无害,有时可能对初学者的可读性有益。
  • 就个人而言,对于初学者来说,我认为根据(1)所需元素的数量设置足够的尺寸是很好的; (2) 对象或变量的类型大小。从这个角度来看,它可能利大于弊。
  • 记住,我们总是可以使用 sizeof( *dup ); .还有一个丢失的 free() 调用。
【解决方案2】:

C 中的字符串是char 数组,其中字符\0 表示字符串的结尾。由于您没有明确添加它,printf 只是从内存中打印值,直到它碰巧遇到终止字符(即,这是未定义行为)。相反,您应该将此字符显式添加到结果字符串中:

char* create_string (char ch, int n)
{
    char* dup = (char*) malloc((n + 1) * sizeof(char));
    /* Added 1 for the '\0' char ---^ */

    int i;
    for (i = 0; i < n; i++)
    {
        dup[i]=ch;
    }

    /* Set the terminating char */
    dup[n] = '\0';

    return dup;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-28
    • 1970-01-01
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 1970-01-01
    • 2020-05-17
    相关资源
    最近更新 更多