读书人

定义字符串变量结尾的\0是什么时候添加

发布时间: 2012-02-19 19:43:37 作者: rapoo

定义字符串变量结尾的\0是什么时候添加上去的
在程序中定义一个字符串数组a[]="jkjl"或字符串宏,系统会在末尾添加0 ,这个0是什么时候加上去的,怎么验证?

[解决办法]

C/C++ code
    char arr[4] = "1234";//这样验证
[解决办法]
不是系统添加 0,而是编译器遇到这类 C 字符串的时候处理方法
[解决办法]
1 A string literal is a sequence of characters (as defined in 2.13.2) surrounded by double quotes, optionally
beginning with the letter L, as in "..." or L"...". A string literal that does not begin with L is an ordinary
string literal, also referred to as a narrow string literal. An ordinary string literal has type “array of n
const char” and static storage duration (3.7), where n is the size of the string as defined below, and is
initialized with the given characters. A string literal that begins with L, such as L"asdf", is a wide string
literal. A wide string literal has type “array of n const wchar_t” and has static storage duration, where
n is the size of the string as defined below, and is initialized with the given characters.
2 Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementationdefined.
The effect of attempting to modify a string literal is undefined.
3 In translation phase 6 (2.1), adjacent narrow string literals are concatenated and adjacent wide string literals
are concatenated. If a narrow string literal token is adjacent to a wide string literal token, the behavior is
undefined. Characters in concatenated strings are kept distinct. [Example:
"\xA" "B"
contains the two characters ’\xA’ and ’B’ after concatenation (and not the single hexadecimal character
’\xAB’). ]
4 After any necessary concatenation, in translation phase 7 (2.1), ’\0’ is appended to every string literal so
that programs that scan a string can find its end.
5 Escape sequences and universal-character-names in string literals have the same meaning as in character literals
(2.13.2), except that the single quote ’ is representable either by itself or by the escape sequence \’,
and the double quote " shall be preceded by a \. In a narrow string literal, a universal-character-name may
map to more than one char element due to multibyte encoding. The size of a wide string literal is the total
number of escape sequences, universal-character-names, and other characters, plus one for the terminating
L’\0’. The size of a narrow string literal is the total number of escape sequences and other characters,
plus at least one for the multibyte encoding of each universal-character-name, plus one for the terminating
’\0’.
[解决办法]
末尾的'\0'不是系统特性,是C风格字符串字面量的特性。一个C风格字符串字面量具有数组类型,这个数组所包含的元素不仅仅只有当中的字符,还包含末尾的'\0',这个'\0'不是系统添加上去的,而是字符串本身就有的结束符。当使用字符串字面量进行初始化的时候,是用整个数组而不是仅用字符进行初始化。
[解决办法]
只能说编译的时候写在1234后面,不能说是添加到内存中耳

读书人网 >C语言

热点推荐