Hey currently I am working on exercise 13 of K&R - The C programming language. So far I have the following Code:
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#define ARRAY_SIZE 99
int main() {
struct termios old_tio, new_tio;
/* get the terminal settings for stdin */
tcgetattr(STDIN_FILENO, &old_tio);
/* we want to keep the old setting to restore them a the end */
new_tio = old_tio;
/* disable canonical mode (buffered i/o) and local echo */
new_tio.c_lflag &= (~ICANON & ~ECHO);
/* set the new settings immediately */
tcsetattr(STDIN_FILENO, TCSANOW, &new_tio);
int c, length, lengthArray[ARRAY_SIZE], word, lastChar, longestWord;
word = 0;
longestWord = 0;
while ((c = getchar()) != 'q') {
if (c == ' ' || c == '\t' || c == '\n') {
if (lastChar != ' ' && lastChar != '\t' && lastChar != '\n') {
lengthArray[word] = length;
word++;
length = 0;
}
} else {
length++;
if (length > longestWord)
longestWord = length;
}
putchar(c);
lastChar = c;
}
int histogram[longestWord];
for (int i = 0; i < longestWord; i++) {
histogram[i] = 0;
}
for (int i = 0; i < word; i++) {
histogram[lengthArray[i]] += 1;
}
for (int i = 0; i < longestWord; i++) {
printf("%d: %d\n", i, histogram[i]);
}
/* restore the former settings */
tcsetattr(STDIN_FILENO, TCSANOW, &old_tio);
return 0;
}
Everytime I run it I get a segmantation fault, unless I comment out the last for loop
for (int i = 0; i < longestWord; i++) {
printf("%d: %d\n", i, histogram[i]);
}
Commenting out the printf statement doesn't help so the for loop is the problem.
(The actual exercise code starts at int c, length, lengthArray. The Termios stuff is just for disabling canonical mode in the terminal)