嗯,我对 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 字符串函数)如何知道字符串何时完成。
关于c - printf 输出垃圾而不是特定字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47225532/