I'm a complete beginner in C, and currently working through the exercises in the C Programming Language-book by Kernighan and Ritchie. This particular exercise is 1.13, where I'm trying to make a program that outputs a histogram based on the lengths of the words inputted. However, when compiling and running this piece of code, I receive the following error after hitting Enter in the console:
Illegal Instruction: 4
The code itself is definitely faulty and incomplete, but I was simply trying to test it here. The problem is I cannot figure out where this error is coming from. I'm using a Macbook and have tried to specify my OS-version during compilation to gcc, without this helping the problem.
#define WORD 0
#define NONWORD 1
int main(void)
{
int c, i, j;
int state;
int incrementer;
/* This solution only works for word-lengths below 20 characters.
Can be expanded/decreased by resizing wordLengths-array to any given length. */
int wordLengths[20];
while ((c = getchar()) != EOF) {
if (c == ' ' || c == '\t' || c == '\n'){
state = NONWORD;
} else {
state = WORD;
}
if (state == WORD) {
incrementer++;
}
if (state == NONWORD && incrementer != 0) {
wordLengths[incrementer-'1']++;
incrementer = 0;
}
}
for (i = 0; i < sizeof(wordLengths); i++) {
printf("%d |", i);
for (j = 0; j < wordLengths[i]; j++) {
putchar('=');
}
printf("\n");
}
printf("Hello world");
}
Debugger is your best friend. You would immediately realize that your incrementer isn't enough for counting which word is it at, or for being used as your array's index.
One of the possibilities would be to introduce a separate variable for counting words and writing measured length to corresponding member of your array
int wcnt = -1;
in the following way:
if (state == WORD) {
if(incrementer == 0)wcnt++;
incrementer++;
}
if (state == NONWORD && incrementer != 0) {
wordLengths[wcnt] = incrementer;
incrementer = 0;
}
and also use it for printf()ing the written sizes from the array members:
for (i = 0; i <= wcnt; i++){ … }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With