初始化字符串Initializing Strings

您可以使用字符串文本(或宽字符串文本)初始化字符(或宽字符)的数组。You can initialize an array of characters (or wide characters) with a string literal (or wide string literal). 例如:For example:

char code[ ] = "abc";  

code 初始化为一个四元素字符数组。initializes code as a four-element array of characters. 第四个元素为 null 字符,用于终止所有字符串文本。The fourth element is the null character, which terminates all string literals.

标识符列表的长度值只能与要初始化的标识符的数量相同。An identifier list can only be as long as the number of identifiers to be initialized. 如果指定短于字符串的数组大小,则会忽略多余字符。If you specify an array size that is shorter than the string, the extra characters are ignored. 例如,以下声明将 code 初始化为一个三元素字符数组:For example, the following declaration initializes code as a three-element character array:

char code[3] = "abcd";  

只有初始值设定项的前三个字符将分配给 codeOnly the first three characters of the initializer are assigned to code. 字符 d 和字符串终止 null 字符将被丢弃。The character d and the string-terminating null character are discarded. 请注意,这将创建一个非终止字符串(即,没有 0 值标记其结束的字符串)并生成指示这种情况的诊断消息。Note that this creates an unterminated string (that is, one without a 0 value to mark its end) and generates a diagnostic message indicating this condition.

声明The declaration

char s[] = "abc", t[3] = "abc";  

等同于is identical to

char s[]  = {'a', 'b', 'c', '\0'},   
     t[3] = {'a', 'b', 'c' };  

如果字符串短于指定的数组大小,数组中的剩余元素将初始化为 0。If the string is shorter than the specified array size, the remaining elements of the array are initialized to 0.

Microsoft 专用Microsoft Specific

在 Microsoft C 中,字符串文本的长度最大为 2048 个字节。In Microsoft C, string literals can be up to 2048 bytes in length.

结束 Microsoft 专用END Microsoft Specific

另请参阅See Also

初始化Initialization