简体   繁体   English

C程序冻结的单词长度大于6

[英]C program freezes for word lengths greater than 6

I'm working through the first chapter of K&R and came to the exercise where you're supposed to create a histogram of word lengths for some input. 我正在研究K&R的第一章,并完成了本练习,在该练习中您应该为某些输入创建单词长度的直方图。 I started by trying to use a while loop to create an array of zeros as long as the longest word, but inputs with words longer than six characters cause the program to freeze. 我首先尝试使用while循环来创建最长的单词组成的零数组,但是输入的单词长度超过六个字符会导致程序冻结。 I'm less interested in just a solution than I am in knowing the cause. 我对解决方案的兴趣不如对原因的了解。

#include <stdio.h>

main()
{
int c, i, l, max;
int length[max];

l = max = 0;

    while((c = getchar()) != EOF){
        if(c != ' ' && c != '\t' && c != '\n'){
            ++l;
            if(l > max)
               max = l;
             else
                 ;
             }
        else
            l = 0;
        }
    for(i = 0; i < max; ++i)
        length[i] = 0;

    for(i = 0; i < max; ++i)    
        printf("\n%d", length[i]);
        putchar('\n');
}

max is uninitialized when length[max] is defined. 定义length[max]时, max未初始化。 Essentially, you're using unallocated memory. 本质上,您正在使用未分配的内存。

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

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