C循环不会退出

Jef*_*ing 0 c

早上好,一个人!事后来看,这最终将成为一个令人眼花缭乱的问题之一,但对于我的生活,我很难过.我正在阅读C语言编程语言中的一些练习,并且我已经设法编写了一些代码来初始化循环.经过一些谷歌搜索,我找到了更好的方法将循环初始化为0,但我不明白为什么我写的循环没有完成.我用调试器发现它是因为'c'变量永远不会达到50,它变为49然后翻到0,但我无法弄清楚为什么它会翻滚.代码附在下面,有谁知道这里发生了什么?

#include <stdio.h>
#define IN 1
#define OUT 0

/* Write a program to print a histogram of the lengths of words in
    itsinput. */
main()
{
    int c=0;
    int histogram[50]={0}
    int current_length=0;
    int state=OUT;

    //Here we borrow C so we don't have to use i
    printf("Initializing...\n");
    while(c<51){
        histogram[c] =0;
        c=c+1;
    }
    c=0;
    printf("Done\n");

    while( (c=getchar()) != EOF){
        if( (c==32 || c==10) && state==IN ){
            //End of word
            state=OUT;
            histogram[current_length++];
        }else if( (c>=33 && c<=126) && state==OUT ){
            //Start of word
            state=IN;
            current_length=0;
        }else if( (c>=33 && c<=126) && state==IN ){
            //In a word
            current_length++;
        } else {
            //Not in a word
            //Example, "  " or " \n "
            ;
        }
    }

    //Print the histogram
    //Recycle current_length to hold the length of the longest word
    //Find longest word
    for( c=0; c<50; c++){
        if( c>histogram[c] )
            current_length=histogram[c];
    }
    for( c=current_length; c>=0; c--){
        for( state=0; state<=50; state++){
            if( histogram[c]>=current_length )
                printf("_");
            else
                printf(" ");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

cni*_*tar 5

这是因为histogram[c] = 0写入时通过histogram内存c = 50.所以基本上histogram[50]覆盖c并使其为0.

发生这种情况是因为数组从0C 开始.所以50个元素数组中的最后一个有效索引是49.

从技术上讲,虽然有趣和可利用,但你不能依赖于此.这是未定义行为的表现.内存可能很容易有另一种布局,导致事情"正常工作"或做一些更有趣的事情.