I'm working through K&R exercise 1-13, and I forgot to set the elements in my array to 0. To my surprise, the last value that I got when printing the array was 32767; subsequent tests have different element values for the array, some different, and some not.
I'd like to know why this is happening. If it's highly complex, then what's going on in simple terms?
#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;
}
Input & Corresponding Output:
hello codes
4195584
0
0
0
4196032
2
4195584
0
-1608045280
32767
accum. You never check when it reaches the array limit. Values0..9are ok, after that in extreme cases you may need to scrap the computer, since indexingncharby 10 is very bad.while ((c = getchar()) != EOF && accum < 10) {