【问题标题】:printf outputting garbage instead of specific charactersprintf 输出垃圾而不是特定字符
【发布时间】:2012-11-26 15:31:12
【问题描述】:

我对@9​​87654322@ 有一个奇怪的问题。它在屏幕上输出垃圾。我猜这与记忆有关。看看:

char string1[] = "SAMPLE STRING";
char string2[20]; // some garbage in it

/* let's clear this madness*/
int i = 0;
for (i; i < 20; i++) string2[i] = ' ';   // Space, why not.

printf("output: %s", string2);

输出

output:      ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠SAMPLE STRING
// ten spaces and random characters, why?

【问题讨论】:

标签: c memory printf


【解决方案1】:

因为 C 字符串需要以 NUL 结尾。这意味着您的字符串的最后一个字符必须是'\0'。这就是printf(以及所有其他 C 字符串函数)知道字符串何时完成的方式。

【讨论】:

  • 实际上,它们是 NUL 终止的。 NUL 是 nul 字符,NULL 是 nul 指针。
  • 我会把它写成“空终止”,而不是“空终止”,因为NULL(全部大写)是一个指针,所以它可能会造成混淆。
【解决方案2】:

用空字符 '\0' 结束你的 string2

string2[19] = '\0';

或者你可以这样做:

for (i; i < 19; i++) string2[i] = ' ';
string2[i] = '\0'; // after the end of the loop i= 19 here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2015-04-29
    • 2011-11-21
    • 2017-11-23
    • 2018-02-14
    • 2023-03-20
    相关资源
    最近更新 更多