问题描述
为什么用%s打印空字符('\0',0)会打印出(null)字符串? 像这样的代码:
char null_byte ='\0';
printf(null_byte:%s\\\
,null_byte);
...打印:
null_byte:(null)
...它甚至没有运行Valgrind下的错误,我得到的是编译器警告警告:格式'%s'需要类型为'char *'的参数,但参数2的类型为'int'[-Wformat]
(注意:我在32位Ubuntu上使用gcc 4.6.3)
这是未定义的行为,在您的实施中:您传递的
- 0的
int
值被读取%s
作为空指针 - 处理
%s
byprintf
包含特殊代码以识别空指针并打印(null)
。
这些标准都不需要。所需的部分是* varargs中使用的 char
作为 int
传递。 p>
[*]那么需要考虑到在你的实现中, char
的所有值都可以表示为 INT
。如果您在 char
为无符号且宽度与 int
相同的有趣实现中,它将作为 unsigned int
。我认为有趣的实施将符合标准。
Why does printing a null char ('\0', 0) with %s prints the "(null)" string actually?
Like this code:
char null_byte = '\0';
printf("null_byte: %s\n", null_byte);
...printing:
null_byte: (null)
...and it even runs without errors under Valgrind, all I get is the compiler warning warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat]
(note: I'm using gcc 4.6.3 on 32bit Ubuntu)
It's undefined behavior, but it happens that on your implementation:
- the
int
value of 0 that you pass is read by%s
as a null pointer - the handling of
%s
byprintf
has special-case code to identify a null pointer and print(null)
.
Neither of those is required by the standard. The part that is required[*], is that a char
used in varargs is passed as an int
.
[*] Well, it's required given that on your implementation all values of char
can be represented as int
. If you were on some funny implementation where char
is unsigned and the same width as int
, it would be passed as unsigned int
. I think that funny implementation would conform to the standard.
这篇关于C:为什么用%s打印空字符会打印“(null)”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!