这里发生在for循环 [英] What's happening here in this for loop
问题描述
我是想别的东西却突然卡住这个无限循环。
请建议与解释的答案怎么在这里就在下面的for循环
I was trying something else but suddenly stuck with this infinite loop . Please suggest an answer with explanation that what's going on here in the below for loop
#include<stdio.h>
int main()
{
int x=0;
int i;
int array[5];
for(i=0;i<=5;i++)
{
array[i]=x;
printf("#%d value set in index %d\n",x,i);
}
return 0;
}
当我删除 =
登录的条件
循环正常工作。
When I remove =
sign in the condition of for
loop It works fine.
但是,当我把这个它进入无限循环,为什么呢?
数组访问额外的元素(比限值)是未定义的行为还是什么?
任何帮助将AP preciated。
先谢谢了。
But when I put this it goes to infinite loop , Why? Accessing extra element (more than its limit) in array is undefined behaviour or what ? Any help will appreciated. Thanks in advance.
〜
推荐答案
要避免造成这样的错误,因为很容易,这里有两个很好的规则编写为
遍历实际(本地)数组:
To avoid causing errors like this as easily, here's two good rules for writing for
loops over actual (local) arrays:
- 迭代开始于指数为0,由于C的数组是从0开始。
- 使用
&LT;
,始终。决不&LT; =
- 请不要重复大小,让编译器使用
的sizeof数组/ * sizeof的阵列
计算它。请注意,在第二个任期内的星号。
- Iteration starts at index 0, since C's arrays are 0-based.
- Use
<
, always. Never<=
. - Don't repeat the size, let the compiler compute it using
sizeof array / sizeof *array
. Note the asterisk in the second term.
所以,这个循环应该已被写入:
So, this loop should have been written:
for(i = 0; i < sizeof array / sizeof *array; i++)
,然后你会一直是安全的。
and then you would have been safe.
请注意,这仅适用于真正的阵列具有规模可见的sizeof
,如果你让阵列崩溃为指针它赢得将不起作用。
Note that this only works for "real" arrays that have a size visible to sizeof
, if you've let the array "collapse" into a pointer it won't work.
另外请注意,的sizeof
不是一个功能,因此无需()
是围绕其在案件的说法必要像这样的。
Also note that sizeof
is not a function, so no ()
s are necessary around its argument in cases like these.
这篇关于这里发生在for循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!