简体   繁体   English

非法指令:C 程序中的 4

[英]Illegal Instruction: 4 in C-program

I'm a complete beginner in C, and currently working through the exercises in the C Programming Language-book by Kernighan and Ritchie.我是 C 的完整初学者,目前正在完成 Kernighan 和 Ritchie 编写的 C 编程语言书中的练习。 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.这个特定的练习是 1.13,我正在尝试制作一个程序,根据输入的单词的长度输出直方图。 However, when compiling and running this piece of code, I receive the following error after hitting Enter in the console:但是,在编译和运行这段代码时,我在控制台中按 Enter 后收到以下错误:

Illegal Instruction: 4非法指令: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.我正在使用 Macbook 并尝试在编译到 gcc 期间指定我的操作系统版本,但这对问题没有帮助。

#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.您会立即意识到您的incrementer器不足以计算它所在的单词或用作数组的索引。
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:并将其用于printf() ing 数组成员的写入大小:

for (i = 0; i <= wcnt; i++){ … }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM