简体   繁体   English

为什么代码进入无限循环

[英]Why the code goes into Infinite Loop

I have just started with C and have been following "The C Programming Language" 2nd Edition by Kernighan and Ritchie. 我刚开始使用C,并且一直关注Kernighan和Ritchie撰写的“ The C Programming Language”第二版。 I am solving the Excercise 1.14 to print histogram for the frequencies of characters. 我正在解决Excercise 1.14来打印字符频率的直方图。 Heres my code 这是我的代码

#include<stdio.h>
#define FIRST_GRAPHIC_CHAR 32
#define LAST_GRAPHIC_CHAR 126
#define NUM_GRAPHIC_CHARS (LAST_GRAPHIC_CHAR - FIRST_GRAPHIC_CHAR + 1)
int main(void)
{
  int c,thisval,maxval,i,j;
  int frequency[NUM_GRAPHIC_CHARS] = { 0 };
  c=getchar();
  while(c>=FIRST_GRAPHIC_CHAR && c<=LAST_GRAPHIC_CHAR && c != '\n')
    {
      ++frequency[c-FIRST_GRAPHIC_CHAR];
      c=getchar();
    }
  printf("CASE \t\tOccurences\n");
  for(i=0;i<=NUM_GRAPHIC_CHARS;i++)
  {
    if(i+FIRST_GRAPHIC_CHAR == ' ')
    {
      printf("<space> |\t");
      for(j=0;j<frequency[i];j++)
       {
          printf("*");
       }
      printf("\n");
     }
   else
   {
     printf("%c \t|\t",i+FIRST_GRAPHIC_CHAR);
     for(j=0;j<frequency[i];j++)
     {
        printf("*");
     }
     printf("\n");
    } 
  }
 return(0);
 }

Now my question is when I run this code the program goes into an Infinite loop however when I use the expression 现在我的问题是,当我运行这段代码时,程序会进入无限循环,但是当我使用表达式时

j<frequency[i] istead of
j<=frequency[i] 

in the for loop it works perfectly.Now I am unable to understand why is it going into an infinite loop? 在for循环中它可以完美工作。现在我不明白为什么会进入无限循环? Do tell if something is wrong with the code. 务必告诉代码是否有问题。

You have undefined behavior in your code. 您的代码中有未定义的行为 The outer loop goes from 0 to NUM_GRAPHIC_CHARS inclusive , but you have to remember that arrays have indices from 0 to their size minus one, so you step out of bounds for the frequency array. 外循环从0NUM_GRAPHIC_CHARS 含) ,但是您必须记住,数组的索引从0到其大小减去一,因此您会超出frequency数组的范围。

What will be value be of that out-of-bounds entry? 该越界条目的价值是什么? No one knows, but as it might be large your inner loops might take quite some time, maybe even seem infinite. 没有人知道,但是因为它可能很大,所以内部循环可能会花费一些时间,甚至看起来是无限的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM