I personally prefer using for-loop notation with strtok... and I would write the core loop like this:
if (sizeNames)
{
size_t idx = 0;
char *token;
for( token = strtok(stringLine, delim);
token && idx<count;
token = strtok(NULL, delim), idx++)
{
*(sizeNames + idx) = strdup(token);
}
*(sizeNames + idx) = NULL;
}
But, since you are NULL-terminating after the last word, be sure to use count+1 in the following, or else the above line *(sizeNames + idx) = NULL;
could segfault:
sizeNames = malloc(sizeof(char*) * (count+1));
PS... your countWords routine returns the wrong answer, too. Probably want to replace:
return count-1;
With:
if( (last+1)==tmp )
return count;
return count+1;
Also, the memory you allocate with strdup()
is never freed anywhere, so you will get leak errors if you run this through valgrind.
Note, you don't really have to use strdup()
since strtok()
leaves NULs in the places where it found delimiters in the source string, so you could have written:
*(sizeNames + idx) = token;
in the heart of the for-loop. Because of this destructive behavior, strtok()
is sometimes only run on a copy of a buffer to be analyzed.