strtok

Why is it that changing the following line:

 
char str[] ="- This, a sample string.";


to

 
char * str ="- This, a sample string.";


in the reference example for strtok usage causes a segmentation fault (after the initial printf statement?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char * str ="- This, a sample string.";
  char * pch;
  printf ("Splitting string \"%s\" into tokens:\n",str);
  pch = strtok (str," ,.-");
  while (pch != NULL)
  {
    printf ("%s\n",pch);
    pch = strtok (NULL, " ,.-");
  }
  return 0;
}
Because the first one is modifiable while the second one is a pointer to a string constant.
Got it, thanks!
Topic archived. No new replies allowed.