Using strtok() in a loop in C?
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" */
}