空字符

本页使用了标题或全文手工转换
维基百科,自由的百科全书

空字符Null character)又称结束符,缩写NUL,是一个数值为0的控制字符[1][2]。在许多字符编码中都包括空字符,包括ISO/IEC 646ASCII)、C0控制码英语C0 and C1 control codes通用字符集UnicodeEBCDIC等,几乎所有主流的编程语言都包括有空字符[3]

这个字符原来的意思类似NOP指令,当送到列表机终端时,设备不需作任何的动作(不过有些设备会错误的打印或显示一个空白)。

空字符在C语言及其派生语言及许多资料类型中都非常的重要,在C语言中空字符是字符串的结束码[4],这样的字符串称为空字符终止字符串或ASCIIZ字符串[5]。因此字符串的长度可以为任意自然数,但需多增加一个字符的空间存储空字符。

表示方式[编辑]

在程序源代码的字符串或字符常量中,常用转义序列\0表示空字符[6]。在C语言及其派生语言中,\0不是一个单独的转义序列,而是一个以八进制表示常量,而常量的数值为0,\0后面不能接0至7的数字,不然会视为是一个八进制的数字。其他语言表示空字符的方式包括\000\x00Unicode表示法的\u0000或是\z。在URL中可以用%00表示空字符,若是配合不正确的输入验证,会造成一个称为“空字符注入”(null byte injection)的计算机安全隐患,可能会导致安全性的问题[7]

有时在文件中会用一个其中有NUL字符,大小和一般英文字母同宽的符号来表示空字符。在Unicode中有一个字符是对应空字符的视觉表示方式,即“NUL符号”U+2400 (),但在Unicode中真正的空字符是U+0000。

编程语言会自动在字符串结尾加上结束符,不需由程序员自己打上去。

例如以下的C++代码:

char str[] = "Wikipedia";
cout << str << endl;
 i 0 1 2 3 4 5 6 7 8 9
 str[i]  W i k i p e d i a \0

9个字符加上结束符,该字符串的长度是10。当程序员使用 cout 打印字符串到显示屏,C++程序便由 str 第0格开始,一直打印到结束符。当然,结束符本身并不会打印。

相关条目[编辑]

参考资料[编辑]

  1. ^ ASCII format for Network Interchange: sec. 5.2. RFC 20. NUL (Null): The all-zeros character which may serve to accomplish time fill and media fill. 
  2. ^ The set of control characters of the ISO 646 (PDF). Secretariat ISO/TC 97/SC 2: 4.4. 1975-12-01 [2012-08-15]. (原始内容 (PDF)存档于2012-07-29). Position: 0/0, Name: Null, Abbreviation: Nul 
  3. ^ "A byte with all bits set to 0, called the null character, shall exist in the basic execution character set; it is used to terminate a character string literal." — ANSI/ISO 9899:1990 (the ANSI C standard), section 5.2.1
  4. ^ "A string is a contiguous sequence of characters terminated by and including the first null character" — ANSI/ISO 9899:1990 (the ANSI C standard), section 7.1.1
  5. ^ "A null-terminated byte string, or NTBS, is a character sequence whose highest-addressed element with defined content has the value zero (the terminating null character)" — ISO/IEC 14882 (the ISO C++ standard), section 17.3.2.1.3.1
  6. ^ Kernighan and Ritchie, C, p. 38
  7. ^ Null Byte Injection页面存档备份,存于互联网档案馆) WASC Threat Classification Null Byte Attack section.