C语言中,strtok在递归返回后返回NULL。

6

当我的代码中没有调用相同的函数时,一切都运行良好。但是当函数从递归返回时,变量pch突然为NULL:

 void someFunction()
     {
        char * pch;
        char tempDependencies[100*64+100];
        strcpy(tempDependencies,map[j].filesNeeded);
        pch = strtok(tempDependencies,",");
        while (pch != NULL)
        {
            someFunction(); <- if i comment this out it works fine
            pch = strtok (NULL, ",");
        }
      }

因此,例如,当循环作用于字符串file2,file3,file4时,它会正确地分割file2并修改该字符串为file2\\000file3,file4,但是下一个对pch = strtok(NULL, ",");的调用会导致pch成为0x0。在递归调用时,我没有意识到的问题吗?
2个回答

11

strtok()不可重入。如果您想在递归函数中使用它,必须使用strtok_r()

另请参阅:strtok,strtok_r


5

在上一次执行完成之前,您无法再次调用strtok函数-它不是可重入的

请改用其可重入版本strtok_r


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接