Segmentation Fault when using strtok_r

后端 未结 6 1002
野的像风
野的像风 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:43

    Try this:

    #include 
    #include 
    
    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.
    */
    

提交回复
热议问题