将字符串与用户输入分开而不是将其放入数组的分段错误

Segmentation Fault for separating a string from user input than putting it to a array

我试图从用户输入中获取带有空格的字符串,例如 "abcd12314 asdfg92743 ppoqws21321" 并将它们分开,然后将它们存储在一个数组中。但它给了我一个分段错误

int main() {
    char string[150];
    int i = 0;
    fgets(string, sizeof(string), stdin);
    char *words = strtok(string, " ");
    char *stored[150];

    while (words != NULL) {
        stored[i++] = words;
        words = strtok(NULL, " ");
    }

    for (i = 0; i < strlen(string); i++) {
        printf("%s\n", stored[i]);
    }

    return 0;
}

你想要这个:

int main() {
    char string[150];
    int i = 0;
    fgets(string,sizeof(string),stdin);
    char *words = strtok (string, " ");
    char *stored[150];

    while (words != NULL) {
        stored[i++] = words;
        words = strtok (NULL, " ");
    }

    int nbofwords = i;                 // <<<< add this
    for (i = 0; i < nbofwords; i++) {  // change this line
        printf("%s\n", stored[i]);
    }
    return 0;
}

但是这段代码容易出错,你应该像下面这样写。您应该在第一次使用时声明变量,并直接在 for 语句中声明循环计数器。

int main() {
  char string[150];
  fgets(string, sizeof(string), stdin);

  char* stored[150];
  int nbofwords = 0;
  
  char* words = strtok(string, " ");
  while (words != NULL) {
    stored[nbofwords++] = words;
    words = strtok(NULL, " ");
  }

  for (int i = 0; i < nbofwords; i++) {
    printf("%s\n", stored[i]);
  }

  return 0;
}

免责声明:这是未经测试的代码。