使用较小的字符串初始化char数组

如果我写:
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.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...