Segmentation Fault when using strtok_r

后端 未结 6 1001
野的像风
野的像风 2020-12-14 02:55

Can anyone explain why I am getting segmentation fault in the following example?

#include 
#include 

int main(void) {
  char          


        
6条回答
  •  旧时难觅i
    2020-12-14 03:26

    • You need to call strtok_r in a loop. The first time you give it the string to be tokenized, then you give it NULL as the first parameter.
    • strtok_r takes a char ** as the third parameter. tokens is an array of 50 char * values. When you pass tokens to strtok_r(), what gets passed is a char ** value that points to the first element of that array. This is okay, but you are wasting 49 of the values that are not used at all. You should have char *last; and use &last as the third parameter to strtok_r().
    • strtok_r() modifies its first argument, so you can't pass it something that can't be modified. String literals in C are read-only, so you need something that can be modified: char hello[] = "Hello World, Let me live."; for example.

提交回复
热议问题