gpt4 book ai didi

c - 未初始化的字符数组

转载 作者:行者123 更新时间:2023-11-30 21:17:58 24 4
gpt4 key购买 nike

执行以下代码时我得到输出“ma”。如果我的理解是正确的,局部变量没有初始化为0。那么在这种情况下,为什么%s在a1[2]本身中找到0?我们是否无法预测这种情况下的输出,而我以某种方式得到了这个结果,但情况可能并非总是如此?

int main(void)
{
char a1[10];
a1[0]='m';
a1[1]='a';
a1[3]='j';
printf("%s",a1);
return(0);
}

最佳答案

是的,除非a1静态注意,作为一个自动局部变量,这就是全部靠运气。您的代码(片段)生成 undefined behavior缺少终止 null

它恰好将紧邻的下一个字节设置为null,因此它正确打印。无法保证下次就能正常工作。

FWIW,%s 格式说明符需要一个字符串,而 C 中字符串的定义是null 终止的 char 数组。要复制准确的措辞,

If no l length modifier is present, the argument shall be a pointer to the initial element of an array of character type. [..] If the precision is not specified or is greater than the size of the array, the array shall contain a null character.

<小时/>

注意:与静态变量的初始化相关,引用C11标准,第§6.7.9章,初始化,(强调我的)

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static or thread storage duration is not initialized explicitly, then:

  • [...]

  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;

关于c - 未初始化的字符数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32816845/

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