This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center
                            
                        
                    
                
                                7年前关闭。
            
                    
我在尝试其他方法,但突然陷入了这个无限循环。
请提出一个答案,并解释以下for循环中发生的事情

#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;
}


当我在=循环的条件下删除for标志时,它工作正常。

但是当我把它放到无限循环的时候,为什么呢?
访问数组中的额外元素(超出其限制)是未定义的行为或什么?
任何帮助将不胜感激。
提前致谢。

最佳答案

为了避免像这样容易引起错误,这里有两个关于在实际(本地)数组上编写for循环的好的规则:


迭代从索引0开始,因为C的数组基于0。
始终使用<。请勿<=
不要重复大小,让编译器使用sizeof array / sizeof *array进行计算。请注意第二项中的星号。


因此,该循环应编写为:

for(i = 0; i < sizeof array / sizeof *array; i++)


那你就很安全了

请注意,这仅适用于大小为sizeof可见的“实际”数组,如果您已将数组“折叠”到指针中,则它将不起作用。

另请注意,sizeof不是函数,因此在此类情况下,()不需要围绕其参数。

关于c - 此for循环在这里发生了什么,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13010004/

10-12 12:39
查看更多