[英]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.