C 程序冻结字长大于 6
C program freezes for word lengths greater than 6
我正在学习 K&R 的第一章,然后来到练习中,您应该为某些输入创建字长直方图。我开始尝试使用 while 循环来创建一个与最长单词一样长的零数组,但是输入超过六个字符的单词会导致程序冻结。与了解原因相比,我对解决方案更感兴趣。
#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
在定义 length[max]
时未初始化。本质上,您正在使用未分配的内存。
我正在学习 K&R 的第一章,然后来到练习中,您应该为某些输入创建字长直方图。我开始尝试使用 while 循环来创建一个与最长单词一样长的零数组,但是输入超过六个字符的单词会导致程序冻结。与了解原因相比,我对解决方案更感兴趣。
#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
在定义 length[max]
时未初始化。本质上,您正在使用未分配的内存。