使用strtok_r时出现分段错误

Phu*_*e 2 16 c strtok segmentation-fault

任何人都可以解释为什么我在下面的例子中得到分段错误?

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

int main(void) {
  char *hello = "Hello World, Let me live.";
  char *tokens[50];
  strtok_r(hello, " ,", tokens);
  int i = 0;
  while(i < 5) {
    printf("%s\n", tokens[i++]);
  }
}
Run Code Online (Sandbox Code Playgroud)

cod*_*ict 24

试试这个:

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

int main(void) {
        char hello[] = "Hello World, Let me live."; // make this a char array not a pointer to literal.
        char *rest; // to point to the rest of the string after token extraction.
        char *token; // to point to the actual token returned.
        char *ptr = hello; // make q point to start of hello.

        // loop till strtok_r returns NULL.
        while(token = strtok_r(ptr, " ,", &rest)) {

                printf("%s\n", token); // print the token returned.
                ptr = rest; // rest contains the left over part..assign it to ptr...and start tokenizing again.    
        }
}
/*
Output:
Hello
World
Let
me
live.
*/
Run Code Online (Sandbox Code Playgroud)


Alo*_*hal 16

  • 你需要strtok_r循环调用.第一次给它提供要标记化的字符串,然后将其NULL作为第一个参数给出.
  • strtok_r将a char **作为第三个参数. tokens是一个包含50个char *值的数组.传递tokensstrtok_r()传递的是一个char **指向该数组的第一个元素的值.这没关系,但是你浪费了49个根本没用过的值.你应该拥有char *last;并使用它&last作为第三个参数strtok_r().
  • strtok_r()修改其第一个参数,因此您无法将其传递给无法修改的内容.C中的字符串文字是只读的,因此您需要一些可以修改的内容:char hello[] = "Hello World, Let me live.";例如.


jam*_*lin 5

一堆错误:

  1. hello指向字符串文字,必须将其视为不可变.(它可以存在于只读内存中.)由于strtok_r改变了它的参数字符串,所以你不能使用hello它.

  2. strtok_r只调用一次并且不初始化tokens数组以指向任何内容.

试试这个:

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

int main(void) {
  char hello[] = "Hello World, Let me live.";
  char *p = hello;
  char *tokens[50];
  int i = 0;

  while (i < 50) {
     tokens[i] = strtok_r(p, " ,", &p);
     if (tokens[i] == NULL) {
        break;
     }
     i++;
  }

  i = 0;
  while (i < 5) {
    printf("%s\n", tokens[i++]);
  }

  return 0;
}
Run Code Online (Sandbox Code Playgroud)