printf输出垃圾而不是特定字符 [英] printf outputting garbage instead of specific characters
本文介绍了printf输出垃圾而不是特定字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
好吧,我对printf()
感到奇怪.它在屏幕上输出垃圾.我猜这与记忆有关.看看:
Well I've weird problem with printf()
. It's outputting garbage on screen. It's kind of connected with memory I guess. Have a look:
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字符串函数)如何在字符串完成时知道的.
Because C strings need to be NUL terminated. This means the last char of your string must be '\0'
. This is how printf
(and all other C string functions) know when a string is finished.
这篇关于printf输出垃圾而不是特定字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文