gpt4 book ai didi

c - 为什么这个 for 循环会影响外部循环的变量?

转载 作者:太空宇宙 更新时间:2023-11-04 06:40:05 24 4
gpt4 key购买 nike

我正在做作业,尝试简化代码并得到相同的结果。

unsigned char x=5;
byte a1[100];
/*byte a1 is then filled*/
byte a2[7];
int counter = 0;

for (counter=0;counter!=8;counter++)
{
a2[counter]=a1[counter];
printf("%d ",x);
}

结果是 5 5 5 5 5 5 5 ?
在哪里 ?是一个随机数

我很困惑为什么会发生这种情况,因为数组甚至与这个变量无关,而且似乎一切都在数组的范围内。是什么原因造成的,或者我该如何解决?

最佳答案

你正在写超过数组的末尾。写入 a2[7] 是未定义的行为(在您的情况下,它立即写入堆栈中数组之后的变量)。

要解决这个问题,要么在 7 处结束循环,要么声明 byte a2[8];

关于c - 为什么这个 for 循环会影响外部循环的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9877226/

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