C:为什么用%s打印空字符会打印“(null)”? [英] C: why printing a null char with %s prints "(null)"?

查看:608
本文介绍了C:为什么用%s打印空字符会打印“(null)”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么用%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 by printf 包含特殊代码以识别空指针并打印(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 by printf 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)”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆