I am working on splitting strings.
When I run this code, I got an error ( Bus error: 10
on MacOs or SegFault on Linux).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char *str = (char *)malloc(1000*sizeof(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;
}
When I change the str declaration by char str[] ="- This, a sample string.";
it works well.
Can anyone tell me why? My brain is melting.