为什么会出现在我的计划无限循环? [英] Why is there an infinite loop in my program?
问题描述
int main(void)
{
int i;
int array[5];
for (i = 0; i <= 20; i++)
array[i] = 0;
return 0;
}
为什么上面的code停留在一个无限循环?
Why is the above code stuck in an infinite loop?
推荐答案
下面是happenning在给定的code。
Here is what happenning in the given code.
#include<stdio.h>
#include<string.h>
int main(void)
{
int i;
int array[5];
for (i = 0; i <= 20; i++)
{
printf("%p %p \n",&i,&array[i]);
printf("the value of i is %d \n",i);
sleep(1);
array[i] = 0;
printf("i may be modified here lets see what i is %d \n", i);
}
return 0;
}
在我的堆栈内存给我的地址位置为
in my stack memory I got the address locations as
I
存储在位置0xbfd1048c地址
i
is stored at location 0xbfd1048c address
和阵列
存储在位置0xbfd10478地址
and array
is stored at location 0xbfd10478 address
当你在一个时间点递增 I
值为每个循环数组的地址[I]
相当于地址 I
(它只是指针引用)
As you are incrementing i
value for each loop at one point of time the address of array[i]
is equivalent to address of i
(its just pointer dereferencing)
您在数组[我]
存储了那么什么是什么,但 I
的实例地址,所以你是在写 I
的实例值,以0作为你提到的数组[我] = 0
相当于到 I = 0
这样的条件 I&LT; = 20
总是成功
So what you are storing at array[i]
is nothing but the i
's instance address so you are over writing the i
's instance value to 0 as you have mentioned array[i] = 0
which is equivalent to i=0
so the condition i<=20
always succeeds.
现在为什么内存以这样一种方式分配的大问题。
Now the BIG question why does the memory allocated in such a way.
这是在运行时间和资源的可用性内核决定。
It is decided at run time and on the availability of the resources to the kernel.
所以这就是为什么我们与数组的限制居住。
So that's why we have to dwell with in the limits of the array.
这篇关于为什么会出现在我的计划无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!