好吧,我有一个奇怪的问题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)
因为C字符串需要NUL终止.这意味着你的字符串的最后一个字符必须是'\0'.这是printf(以及所有其他C字符串函数)知道字符串何时完成的方式.