printf输出垃圾而不是特定字符

krz*_*kov 0 c memory printf

好吧,我有一个奇怪的问题printf().它在屏幕上输出垃圾.我想这与记忆有关.看一看:

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);
Run Code Online (Sandbox Code Playgroud)

OUTPUT

output:      ???????????????????????????SAMPLE STRING
// ten spaces and random characters, why?
Run Code Online (Sandbox Code Playgroud)

Alf*_*nso 8

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

  • 我会将其写为“空终止”,而不是“空终止”,因为“NULL”(全部大写)是一个指针,因此可能会造成混淆。 (4认同)
  • 实际上,它们是以 NUL 结尾的。NUL是nul字符,NULL是nul指针。 (2认同)