开发者

strtok fails to tokenize?

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()开发者_C百科
{
    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'
    }
}


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().


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜