什么是C语言中的字符串文字?
字符串文字是一系列字符,以零结尾。例如,
Char * str = "hi, hello"; /* string literal */
字符串文字用于初始化数组。
char a1[] = "xyz"; /* a1 is char[4] holding {'x','y','z','\0'} */ char a2[4] = "xyz"; /* same as a1 */ char a3[3] = "xyz"; /* a1 is char[3] holding {'x,'y','z'}, missing the '\0' */
如果您尝试更改字符串文字的值,则字符串文字不可修改,这将导致未定义的行为。
char* s = "welcome"; s[0] = 'W'; /* undefined behaviour */
始终尝试使用const这样表示字符串文字。
char const* s1 = "welcome"; s1[0] = 'W'; /* compiler error! */
字符串文字也称为字符常量,它支持不同的字符集。
/* normal string literal, of type char[] */ char* s1 = "abc"; /* UTF-8 string literal, of type char[] */ char* s3 = u8"abc"; /* 16-bit wide string literal, of type char16x[] */ char16x* s4 = u"abc"; /* 32-bit wide string literal, of type char32x[] */ char32x* s5 = U"abc";