Error in strtok function in C

I am using a simple program tokenize strings using the strtok function. Here is the code -

# include <stdio.h>
char str[] = "now # time for all # good men to # aid of their country";   //line a
char delims[] = "#";
char *result = NULL;
result = strtok( str, delims );
while( result != NULL ) {
    printf( "result is \"%s\"\n", result );
    result = strtok( NULL, delims );
}

The program is working successfully. However, if string a is changed to

char * str= "now # time for all # good men to # aid of their country";   //line a 

The strtok function dumps the kernel. I would like an explanation for my understanding of why this is so. Because from the declaration strtok as - char * strtok (char * str1, const char * str2); char * str since the first argument should work

+3
source share
3 answers

You cannot change a string literal. Interaction with the object explains this best. In a nutshell, if you announce

char *stuff = "Read-only stuff";

You cannot change it.

, strtok char *, , , . c faq.

+5

char *str = "foo" ( const char *, C const ).

undefined . strtok .

+6

, . , strdup() , strtok(). , () , , malloced.

+1

All Articles