为什么在添加第二个for循环后,第一个for循环是无限循环 [英] Why first for loop is infinite loop after adding second for loop

查看:153
本文介绍了为什么在添加第二个for循环后,第一个for循环是无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int main()
{
	int x(5),a[7],i(0);

	for(i=0;i<8;i++)
	{
        a[i] = 0;
        cout << "i=" << i <<endl;
        cout << "a[" <<i <<"]=" <<a[i]<<endl;
	}
	for(i=7;i>=0;i++)
	{
		a[i]=x%2;
		cout << "a[" <<i <<"]=" <<a[i]<<endl;
		x=x/2;
		if(x<2)
		{
			i--;
			a[i]=x;
			break;
		}
	}

}

推荐答案

看看你的代码:

Look at your code:
int x(5),a[7],i(0);

for(i=0;i<8;i++)
{
a[i] = 0;
...
}



所以你的数组 a 有7个元素,而你将0写入第一个8.

当你写第8个元素时,它会超出数组,并写入下一个内存位置 - 其中包含变量 i 。因此,在循环第8次循环后,它会查看 i 并看到它为零,所以它再次循环......再次......


So your array a has 7 elements, and you write 0 into the first 8.
When you write the 8th element, it overruns the array, and writes into the next memory location - which contains the variable i. So after the 8th time round the loop, it looks at i and sees it is zero, so it goes round again... And again...


这篇关于为什么在添加第二个for循环后,第一个for循环是无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆