我正在通過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){' –