Using strtok() in nested loops in C?

Alex Xander picture Alex Xander · Oct 2, 2009 · Viewed 12k times · Source

I am trying to use strtok() in nested loops but this is not giving me desired results, possibly because they are using the same memory location. My code is of the form:-

char *token1 = strtok(Str1, "%");
while (token1 != NULL)
{
    char *token2 = strtok(Str2, "%");
    while (token2 != NULL)
    {
        //Do something
        token2 = strtok(NULL, "%");
    }
    // Do something more
    token1 = strtok(NULL, "%");
}

Answer

Alex B picture Alex B · Oct 2, 2009

Yes, strtok(), indeed, uses some static memory to save its context between invocations. Use a reentrant version of strtok(), strtok_r() instead, or strtok_s() if you are using VS (identical to strtok_r()).

It has an additional context argument, and you can use different contexts in different loops.

char *tok, *saved;
for (tok = strtok_r(str, "%", &saved); tok; tok = strtok_r(NULL, "%", &saved))
{
    /* Do something with "tok" */
}