I am using a simple program to tokenize a string using 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 runs successfully. However, if line a is changed to
char * str= "now # time for all # good men to # aid of their country"; //line a
The strtok function gives a core dump. I would like to get an explanation for my understanding why this is so ? Because from the declaration of strtok as –char *strtok( char *str1, const char *str2 ); char *str as the first argument should work
You can’t modify a string literal. The c faq on the subject explains it best. In a nutshell if you declare
You can’t modify it.
The fact that strtok accepts a
char *is related to the fact that you can’t pass arrays to functions, you can only pass addresses. Another c faq entry might help here.