I want to break down a sentence and store each string in an array. Here is my code:
#include <stdio.h>
#include <string.h>
int main(void)
{
int i = 0;
char* strArray[40];
char* writablestring= "The C Programming Language";
char *token = strtok(writablestring, " ");
while(token != NULL)
{
strcpy(strArray[i], token);
printf("[%s]\n", token);
token = strtok(NULL, " ");
i++;
}
return 0;
}
It keeps giving me segmentation error and I cannot figure it out. I believe it has something to do when I copy the token to my array.
Have a look at the example in the docs:
...where...
You need that first string to me modifiable and you need to allocate memory for the outputs e.g.
It's because
writablestring
isn't writable at all. Attempting to write to a string literal is undefined behavior andstrtok
writes to it (that's right,strtok
modifies its argument).To make it work, try:
There's also a C FAQ.
Another problem is that you didn't allocate memory for your array of character pointers (so those pointers point to nothing).
Maybe try this ?