Question

In the following, I'm trying to split string without creating copies using strok

#include <string.h>

void func(char *c)
{
    char *pch = strtok (c,"#");

    while (pch != NULL)
    {
        pch = strtok (NULL, "#");
    }
}

int main()
{
    char c[] = "a#a\nb#b\n";

    char *pch = strtok (c,"\n");

    while (pch != NULL)
    {
        char *p = new char[strlen(pch)+1];
        strcpy(p, pch);

        func(p); //copy of pch

        pch = strtok (NULL, "\n"); //fails to get pointer to 'b#b'
    }
}
Was it helpful?

Solution

Uhm... strtok() may store the tokenized string in a static buffer. Hence, when second strtok() is called in the func(), the results of the first operation (in the main()) seem to be lost. Take a look at strtok_r().

OTHER TIPS

strtok use static variables, therefore it cannot work reentrant and is never threadsafe. strtok_r is not C89/C99 only POSIX.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top