嗯,我有一个奇怪的问题
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);
output: ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠SAMPLE STRING
// Ten spaces and random characters, why?
因为C字符串需要以NUL结尾。这意味着字符串的最后一个字符必须是
'\0'
。这就是 printf
(以及所有其他 C 字符串函数)知道字符串何时完成的方式。
用空字符完成
string2
,'\0'
:
string2[19] = '\0';
或者你可以这样做:
for (i; i < 19; i++)
string2[i] = ' ';
string2[i] = '\0'; // After the end of the loop, i=19 here