【问题标题】:Segmentation fault (core dumped) issue分段错误(核心转储)问题
【发布时间】:2013-09-14 20:24:47
【问题描述】:

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

#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)

知道为什么会发生此错误吗?提前感谢您的帮助!

【问题讨论】:

  • 您查看过崩溃时的堆栈跟踪吗?

标签: c arrays segmentation-fault


【解决方案1】:
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]);  

【讨论】:

  • 您的第一个版本(字符串数组)将不起作用——查看while (space != NULL) 循环。它必须是一个指针数组。
  • 将其更改为 char tokens[100][30] 会产生错误 error: incompatible types when assigning to type ‘char *[30]’ from type ‘char *’
  • 请使用这个 char *tokens[100];
  • @flexcalibur6 你必须声明为char* tokens[100] = {NULL};,也要注意最后一个循环
  • @GrijeshChauhan 你到底在最后一个循环中指出了什么?
猜你喜欢
  • 2018-07-28
  • 2015-06-27
  • 1970-01-01
  • 2021-06-03
  • 2023-04-04
  • 2015-06-25
  • 2021-06-03
相关资源
最近更新 更多