使用 strtok_r 时出现分段错误
谁能解释为什么我在下面的示例中遇到分段错误?
#include <stdio.h>
#include <string.h>
int main(void) {
char *hello = "Hello World, Let me live.";
char *tokens[50];
strtok_r(hello, " ,", tokens);
int i = 0;
while(i < 5) {
printf("%s\n", tokens[i++]);
}
}
Can anyone explain why I am getting segmentation fault in the following example?
#include <stdio.h>
#include <string.h>
int main(void) {
char *hello = "Hello World, Let me live.";
char *tokens[50];
strtok_r(hello, " ,", tokens);
int i = 0;
while(i < 5) {
printf("%s\n", tokens[i++]);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
试试这个:
Try this:
strtok_r
。第一次给它要标记化的字符串时,您将它的NULL
作为第一个参数。strtok_r
采用char **
作为第三个参数。tokens
是一个包含 50 个char *
值的数组。当您将tokens
传递给strtok_r()
时,传递的是一个char **
值,该值指向该数组的第一个元素。这没关系,但是您浪费了 49 个根本没有使用的值。您应该使用char *last;
并使用&last
作为strtok_r()
的第三个参数。strtok_r()
修改其第一个参数,因此您不能向其传递无法修改的内容。 C 中的字符串文字是只读的,因此您需要可以修改的内容:例如char hello[] = "Hello World, Let me live.";
。strtok_r
in a loop. The first time you give it the string to be tokenized, then you give itNULL
as the first parameter.strtok_r
takes achar **
as the third parameter.tokens
is an array of 50char *
values. When you passtokens
tostrtok_r()
, what gets passed is achar **
value that points to the first element of that array. This is okay, but you are wasting 49 of the values that are not used at all. You should havechar *last;
and use&last
as the third parameter tostrtok_r()
.strtok_r()
modifies its first argument, so you can't pass it something that can't be modified. String literals in C are read-only, so you need something that can be modified:char hello[] = "Hello World, Let me live.";
for example.一堆错误:
hello
指向一个字符串文字,它必须被视为不可变的。 (它可以存在于只读内存中。)由于strtok_r
会改变其参数字符串,因此您不能将hello
与它一起使用。您仅调用
strtok_r
一次,并且不会初始化您的tokens
数组以指向任何内容。试试这个:
A bunch of things wrong:
hello
points to a string literal, which must be treated as immutable. (It could live in read-only memory.) Sincestrtok_r
mutates its argument string, you can't usehello
with it.You call
strtok_r
only once and don't initialize yourtokens
array to point to anything.Try this:
strtok_r 尝试将空字符写入 hello (这是非法的,因为它是 const 字符串)
strtok_r tries to write null characters into hello (which is illegal because it is a const string)
您错误地理解了 strtok_r 的用法。请检查此示例和文档
并尝试&看到这个:
You have understood the usage of strtok_r incorrectly. Please check this example and documentation
And try & see this:
我认为它可能是 char *tokens[50]; ,因为当它已经是指针时您将其声明为指针。数组在声明时就已经是一个指针。您的意思是
char tokens[50];
。那应该可以解决问题。I think it might be the
char *tokens[50];
because you are declaring it a pointer when it is already a pointer. An array is already a pointer upon declaration. You mean to saychar tokens[50];
. That should do the trick.