0

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)

Jonas1_4
  • 13
  • 1
  • 5

1 Answers1

-1

int histogram[longestWord]; In an array declaration, the size must be known at compile time. You cant specify a size that histogram known only at runtime.

  • https://stackoverflow.com/questions/31199566/whats-the-difference-between-a-vla-and-dynamic-memory-allocation-via-malloc They were introduced with C99, while the asker mentions K&R, though. – Bob__ Sep 03 '22 at 15:04
  • 1
    Variable length arrays are legal in C. Whether they're a good idea or not is another issue. – Chris Sep 03 '22 at 15:05
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Sep 09 '22 at 10:23