这里发生在for循环 [英] What's happening here in this for loop

查看:127
本文介绍了这里发生在for循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是想别的东西却突然卡住这个无限循环。
请建议与解释的答案怎么在这里就在下面的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:


  1. 迭代开始于指数为0,由于C的数组是从0开始。

  2. 使用&LT; ,始终。决不&LT; =

  3. 请不要重复大小,让编译器使用的sizeof数组/ * sizeof的阵列计算它。请注意,在第二个任期内的星号。

  1. Iteration starts at index 0, since C's arrays are 0-based.
  2. Use <, always. Never <=.
  3. 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屋!

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