[英]Segmentation Fault when using 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++]);
}
}
试试这个:
#include <stdio.h>
#include <string.h>
int main(void) {
char hello[] = "Hello World, Let me live."; // make this a char array not a pointer to literal.
char *rest; // to point to the rest of the string after token extraction.
char *token; // to point to the actual token returned.
char *ptr = hello; // make q point to start of hello.
// loop till strtok_r returns NULL.
while(token = strtok_r(ptr, " ,", &rest)) {
printf("%s\n", token); // print the token returned.
ptr = rest; // rest contains the left over part..assign it to ptr...and start tokenizing again.
}
}
/*
Output:
Hello
World
Let
me
live.
*/
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.";
例如。 一堆错误:
hello
指向一个字符串文字,必须将其视为不可变的。 (它可以存在于只读内存中。)由于strtok_r
改变其参数字符串,因此无法使用hello
。
你只调用strtok_r
一次并且不要初始化你的tokens
数组以指向任何东西。
试试这个:
#include <stdio.h>
#include <string.h>
int main(void) {
char hello[] = "Hello World, Let me live.";
char *p = hello;
char *tokens[50];
int i = 0;
while (i < 50) {
tokens[i] = strtok_r(p, " ,", &p);
if (tokens[i] == NULL) {
break;
}
i++;
}
i = 0;
while (i < 5) {
printf("%s\n", tokens[i++]);
}
return 0;
}
strtok_r尝试将空字符写入hello(这是非法的,因为它是一个const字符串)
您已经错误地理解了strtok_r的用法。 请查看此示例和文档
并尝试看看:
#include <stdio.h>
#include <string.h>
int main(void)
{
char hello[] = "Hello World, let me live.";
char *tmp;
char *token = NULL;
for(token = strtok_r(hello, ", ", &tmp);
token != NULL;
token = strtok_r(NULL, ", ", &tmp))
{
printf("%s\n", token);
}
return 0;
}
我认为它可能是char *tokens[50];
因为当它已经是指针时你将它指定为指针。 数组已经是声明时的指针。 你的意思是说char tokens[50];
。 这应该够了吧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.