sizeof("string") 以及字符数组使用字符串初始化

来源:互联网 发布:韩国视频软件 编辑:程序博客网 时间:2024/04/26 13:57

1. sizeof 对于常量字符串求字节长度时,注意C会对常量字符串追加‘\0’这样一个NUL字符(末尾已经有NUL字符),所以会比所见常量字串长度大1

2. 在声明字符数组中使用常量字符串string初始化时,如果声明中未指定数组长度,注意数组长度为sizeof("string")

3. 在声明字符数组中使用常量字符串string初始化时,如果声明中指定了数组长度,且长度大于字符串长度,则剩余数组元素初始化为NUL字符

下面一段code可见其结果:


执行结果:
main: sizeof(st): 3, sizeof(st\0): 4
str1[0] = s , str1[1] = t , str1[2] = r , str1[3] =  is NUL, str1[4] =  is NUL, str1[5] =  is NUL, 
str2[0] = s , str2[1] = t , str2[2] = r , str2[3] =  is NUL, 
str3[0] = s , str3[1] = t , str3[2] = r , str3[3] =  is NUL, str3[4] =  is NUL, 
str4[0] =  , str4[1] = �, str4[2] = ], str4[3] = , str4[4] = �, str4[5] = ,


0 0