2

我正在尝试读取用户的输入,然后标记每个单词并将每个单词放入字符串数组中。最后,打印出数组的内容以供调试。我的代码如下。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main() {

  int MAX_INPUT_SIZE = 200;
  volatile int running = 1;
  while(running) {

    char input[MAX_INPUT_SIZE];
    char tokens[100];

    printf("shell> ");
    fgets(input, MAX_INPUT_SIZE, stdin);

    //tokenize input string, put each token into an array
    char *space;
    space = strtok(input, " ");
    tokens[0] = space;

    int i = 1;
    while (space != NULL) {
      space = strtok(NULL, " ");
      tokens[i] = space;
      ++i;
    }

    for(i = 0; tokens[i] != NULL; i++) {
      printf(tokens[i]);
      printf("\n");
    }

  printf("\n");     //clear any extra spaces

  //return (EXIT_SUCCESS);
  }
}

在“shell>”提示符下输入我的输入后,gcc 给了我以下错误:

Segmentation fault (core dumped)

关于为什么会发生此错误的任何想法?在此先感谢您的帮助!

4

1 回答 1

3
char tokens[100];  

这个声明应该是字符数组(二维字符数组)来保存多个字符串

  char tokens[100][30];   
  //in your case this wont work because you require pointers   
  //while dealing with  `strtok()`

采用

字符指针数组

char *tokens[100];  

这也是错误的

printf(tokens[i]);   

您应该在打印字符串时使用带有格式说明符 %s 的 printf。
像这样改变

printf("%s", tokens[i]);  
于 2013-09-14T20:29:52.360 回答