我正在通过K & R练习1-13工作,并且我忘记将数组中的元素设置为0.令我惊讶的是,打印数组是32767;随后的测试对阵列有不同的元素值,有些不同,有些则不是。在C中初始化int数组而不指定值
我想知道为什么会发生这种情况。如果它非常复杂,那么简单来说会发生什么?
#include <stdio.h>
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* print the length of words as input to a histogram with horizontal bars */
int main() {
int c, i;
int state = OUT;
int accum = 0;
int nchar[10];
while ((c = getchar()) != EOF) {
if (c != ' ' && c != '\n' && c != '\t') {
state = IN;
++accum;
}
else {
state = OUT;
++nchar[accum];
accum = 0;
}
}
for (i = 0; i < 10; ++i)
printf("%d\n", nchar[i]);
return 0;
}
输入&相应的输出:
hello codes
4195584
0
0
0
4196032
2
4195584
0
-1608045280
32767
它被称为“未定义的行为”。没有人设置任何数组值,所以你永远不能说将会发生什么,虽然有时候它可能是可预测的。 –
我更担心你使用'accum'。你从不检查它何时达到数组限制。值'0'..'9'确定,然后在极端情况下,您可能需要取消计算机,因为将'nchar'索引10非常糟糕。 while((c = getchar())!= EOF && accum <10){' –