Using pointer to character as the argument of strtok

Hitokiri :

I try to split the string by using strtok function. But the program become failed if i use the pointer to character as the argument of this function.

If i initialize the string as s2 or s3 the program works well. But if i use pointer to character as s1 the program get Segmentation fault (core dumped).

char *s1 = "1A 2B 3C 4D";
char s2[] = "1A 2B 3C 4D";
char s3[20] = "1A 2B 3C 4D";

The problem is the other functions, printf and strlen work without failure, but only strtok get error.

The complete code below:

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

void split_string(char *s) {
    char * token = strtok(s," ");
    while (token != NULL) {
        printf("%s\n", token);
        token = strtok(NULL, " ");
    }
}

int main()
{
    char *s1 = "1A 2B 3C 4D";
    char s2[] = "1A 2B 3C 4D";
    char s3[20] = "1A 2B 3C 4D";
    printf("size of s1 = %ld, s2 = %ld, s3 = %ld\n", strlen(s1), strlen(s2), strlen(s3));
    printf("s1: %s\ns2: %s\ns3: %s\n",s1,s2,s3);
    printf("split s2: \n");
    split_string(s2);
    printf("split s3: \n");
    split_string(s3);
    printf("split s1: \n");
    split_string(s1);
    return 0;
}

The result after running:

size of s1 = 11, s2 = 11, s3 = 11
s1: 1A 2B 3C 4D
s2: 1A 2B 3C 4D
s3: 1A 2B 3C 4D
split s2: 
1A
2B
3C
4D
split s3: 
1A
2B
3C
4D
split s1: 
Segmentation fault (core dumped)

strtok from man page: char *strtok(char *str, const char *delim);

Please help to understand this problem.

snr :

Battousai, firstly you need to use your reverse side of the katana to achieve your aim by using readable/writable area. If you don't do this, unless the compiler/OS(Kamiya Kaoru) doesn't prevent you, Shishio Makoto may ruin guys important for you and around you via Sojiro Seta, living in your memory such as Sanosuke Sagara, Yahiko Myojin.

strtok writes into the string you give it - overwriting the separator character with null and keeping a pointer to the rest of the string.

char *s1 = "1A 2B 3C 4D"; // you have a pointer to some read-only characters
char s2[] = "1A 2B 3C 4D"; // same, decay into pointer
char s3[20] = "1A 2B 3C 4D"; // a twenty element array of characters that you can do what you like with.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=405442&siteId=1