Well, I declared a global array of chars like this char * strarr[];
in a method I am tokenising a line and try to put everything into that array like this
*line = strtok(s, " ");
while (line != NULL) {
*line = strtok(NULL, " ");
}
seems like this is not working.. How can I fix it?
Thanks
Any number of things could be going wrong with the code you haven’t shown us, such as undefined behaviour by
strtoking a string constatnt, or getting your parameters wrong when calling the function.But the most likely problem from the code we can see is the use of
*lineinstead ofline, assuming thatlineis of typechar *.Use the following code as a baseline:
This outputs:
and should be easily modifiable into something you can use.
Be aware that, if you’re trying to save the character pointers returned from
strtok(which would make sense for using*line), they are transitory and will not be what you expect after you’re done. That’s because modifications are made in-place within the source string. You can do it with something like:Note the specific size of the
wordarray in that code above. The use ofchar * strarr[]in your code, along with the messagetentative array definition assumed to have one elementis almost certainly where the problem lies.If your implementation doesn’t come with a
strdup, you can get a reasonably-priced one here 🙂