嗯,我在使用 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/13567969/