views:

106

answers:

2

strtok wont work correctly when using char *str as the first parameter (not the delimiters string).

Does it have something to do with the area that allocates strings in that notation? (which as far as i know, is a read-only area).

thanks in advance

example:

//char* str ="- This, a sample string.";   // <---doesn't work
char str[] ="- This, a sample string.";   // <---works
char delims[] = " ";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str,delims);
while (pch != NULL)
{
  printf ("%s\n",pch);
  pch = strtok (NULL, delims);
}
return 0;
A: 

strtok modifies its 1st argument.

In your case 1 the argument to strtok is a string literal which cannot be modified and hence strtok fails . But in case 2 the argument is a modifiable char array which strtok modifies and breaks into smaller strings.

codaddict
i see. well, you and the other guy were very helpful, thanks.
bks
+2  A: 

In the first case, you pass a string literal to strtok(). As strtok() modifies this string, and as string literals cannot legally be modified, you end up with undefined behaviour. In the second case, the compiler copies the string into the array. Array contents can be modified, so this code is OK.

anon
i see. wasn't aware of that behavior of the function.thank you
bks