C 的 strtok() 和只读字符串文字 [英] C's strtok() and read only string literals

查看:44
本文介绍了C 的 strtok() 和只读字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

char *strtok(c​​har *s1, const char *s2)

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

对该函数的重复调用会将字符串 s1 拆分为令牌"——即字符串被分解为子字符串,每个都以\0"结尾,其中'\0' 替换任何字符包含在字符串 s2 中.第一个电话使用要标记为 s1 的字符串;后续调用使用 NULL 作为第一个争论.指向开头的指针返回当前令牌的;空值如果没有更多,则返回令牌.

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 工作正常.

I have been trying to use strtok just now and found out that if I pass in a char* into s1, I get a segmentation fault. If I pass in a char[], strtok works fine.

这是为什么?

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

I googled around and the reason seems to be something about how char* is read only and char[] is writeable. A more thorough explanation would be much appreciated.

推荐答案

你将 char * 初始化为什么?

What did you initialize the char * to?

如果类似

char *text = "foobar";

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

then you have a pointer to some read-only characters

为了

char text[7] = "foobar";

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

then you have a seven element array of characters that you can do what you like with.

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

strtok writes into the string you give it - overwriting the separator character with null and keeping a pointer to the rest of the string.

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

Hence, if you pass it a read-only string, it will attempt to write to it, and you get a segfault.

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

Also, becasue strtok keeps a reference to the rest of the string, it's not reeentrant - you can use it only on one string at a time. It's best avoided, really - consider strsep(3) instead - see, for example, here: http://www.rt.com/man/strsep.3.html (although that still writes into the string so has the same read-only/segfault issue)

这篇关于C 的 strtok() 和只读字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆