gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 16:40:00 25 4
gpt4 key购买 nike

如果我写:

char arr[8] = "abc";

arr[4] 有什么规范吗?我做了一些测试Clang 并且数组中的剩余字符似乎设置为空。此外,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:33           char arr[8] = "abc";(gdb) sCurrent language:  auto; currently minimal4           strcpy(arr, "1234567");(gdb) p arr$1 = "abc\000\000\000\000"(gdb) c      Continuing.Breakpoint 1, a () at str.c:33           char arr[8] = "abc";(gdb) p arr$2 = "1234567"(gdb) s4           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 - 使用较小的字符串文字初始化 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8244453/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com