如果我写:
char arr[8] = "abc";
有没有什么规定什么arr [4]可能是?我做了一些测试
Clang并且似乎数组中的剩余字符设置为null.
另外,char arr [8] =“”;每个字节为零.不知道这是否是编译器
方便,标准行为,纯巧合或错误.
void a() { char arr[8] = "abc"; /* breakpoint here,line 3 */ strcpy(arr,"1234567"); } int main() { a(); a(); return 0; }
调试器成绩单
Breakpoint 1,a () at str.c:3 3 char arr[8] = "abc"; (gdb) s Current language: auto; currently minimal 4 strcpy(arr,"1234567"); (gdb) p arr $1 = "abc\000\000\000\000" (gdb) c Continuing. Breakpoint 1,a () at str.c:3 3 char arr[8] = "abc"; (gdb) p arr $2 = "1234567" (gdb) s 4 strcpy(arr,"1234567"); (gdb) p arr $3 = "abc\000\000\000\000"
解决方法
这是标准行为.
arr [3]被初始化为0,因为终止0是字符串文字的一部分.
所有剩余元素都初始化为0 – ISO/IEC 9899:1999,6.7.8,21:
If there are fewer initializers in a brace-enclosed list than there are elements or members
of an aggregate,or fewer characters in a string literal used to initialize an array of known
size than there are elements in the array,the remainder of the aggregate shall be
initialized implicitly the same as objects that have static storage duration.
并且具有静态存储的char对象将初始化为0.