gpt4 book ai didi

c - 使用 strtok_r 时出现段错误

转载 作者:太空狗 更新时间:2023-10-29 16:31:26 25 4
gpt4 key购买 nike

谁能解释为什么我在下面的示例中出现段错误?

#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.
*/

关于c - 使用 strtok_r 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2227198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com