C 的 strtok() 和只读字符串文字

标签 c string strtok

char *strtok(char *s1, const char *s2)

repeated calls to this function break string s1 into "tokens"--that is the string is broken into substrings, each terminating with a '\0', where the '\0' replaces any characters contained in string s2. The first call uses the string to be tokenized as s1; subsequent calls use NULL as the first argument. A pointer to the beginning of the current token is returned; NULL is returned if there are no more tokens.

你好,

我刚才一直在尝试使用 strtok,发现如果我将 char* 传递给 s1,我会得到一个分段故障。如果我传入 char[]strtok 可以正常工作。

这是为什么?

我用谷歌搜索了一下,原因似乎与 char* 是只读的而 char[] 是可写的有关。更详尽的解释将不胜感激。

最佳答案

您将 char * 初始化为什么?

如果是这样

char *text = "foobar";

然后你有一个指向一些只读字符的指针

为了

char text[7] = "foobar";

然后你就有了一个七元素的字符数组,你可以用它来做你喜欢的事情。

strtok 写入您提供的字符串 - 用 null 覆盖分隔符并保留指向字符串其余部分的指针。

因此,如果您向它传递一个只读字符串,它会尝试写入它,并且您会得到一个段错误。

此外,因为 strtok 保留对字符串其余部分的引用,所以它不可重入 - 您一次只能在一个字符串上使用它。最好避免,真的 - 考虑使用 strsep(3) - 例如,参见此处:http://www.rt.com/man/strsep.3.html (尽管它仍然写入字符串,因此具有相同的只读/段错误问题)

关于C 的 strtok() 和只读字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/272876/

相关文章:

c - 从 strtok() 获取零长度字符串

c - 如何使用strtok将用户输入的单词分隔符分隔为空格

c - 管道系统调用

Python string.letters 不包括语言环境变音符号

java - ReplaceAll() 替换错误的子串

string - 匹配不同长度的字符串前缀

c++ - 防止简单的宏替换

c - 如何消除有关 __FUNCTION__ 的 GCC 迂腐 (-Wpedantic) 警告

c - 如何检查给定参数是否是另一个给定参数的子字符串

c++ - 调用 strtok() 时发生访问冲突; C++