I tried using strtok to split a string and store individual words in a 2D array.I have put printf statements and checked whether individual words are getting stored or not and saw that words are getting stored. But the problem is while loop does not terminate at all, while executing it does not print exit statement "Hi". I am unable to find the mistake here. Can someone help me with this?
int wordBreak(char* str, char words[MAX_WORDS][MAX_WORD_LENGTH])
{
int x=0;
const char *delimiters = " :,;\n";
char* token = strtok(str,delimiters);
strcpy(words[x],token);
x++;
while(token!=NULL) {
token = strtok(NULL,delimiters);
strcpy(words[x],token);
x++;
}
printf("Hi\n");
return x;
}
You must always ensure the return of strtok
is not NULL
before calling strcpy
to copy to your array. A simple rearrangement will ensure that is the case:
int wordBreak (char* str, char words[MAX_WORDS][MAX_WORD_LENGTH])
{
int x = 0;
const char *delimiters = " :,;\n";
char *token = strtok (str,delimiters);
while (x < MAX_WORDS && token != NULL) {
if (strlen (token) < MAX_WORD_LENGTH) {
strcpy (words[x++], token);
token = strtok (NULL, delimiters);
}
else
fprintf (stderr, "warning: token '%s' exeeded MAX_WORD_LENGTH - skipped\n",
token);
}
return x;
}
You also must ensure x < MAX_WORDS
by adding the additional condition as shown above and a test to ensure strlen(token) < MAX_WORD_LENGTH
before copying to your array.