Possible Duplicate:
strtok wont accept: char *str
When using the strtok function, using a char * instead of a char [] results in a segmentation fault.
This runs properly:
char string[] = "hello world";
char *result = strtok(string, " ");
This causes a segmentation fault:
char *string = "hello world";
char *result = strtok(string, " ");
Can anyone explain what causes this difference in behaviour?
This line initializes
stringto be a big-enough array of characters (in this casechar[12]). It copies those characters into your local array as though you had written outThe other line:
does not initialize a local array, it just initializes a local pointer. The compiler is allowed to set it to a pointer to an array which you’re not allowed to change, as though the code were
The reason C allows this without a cast is mainly to let ancient code continue compiling. You should pretend that the type of a string literal in your source code is
const char[], which can convert toconst char*, but never convert it to achar*.