使用 strtok

编程入门 行业动态 更新时间:2024-10-26 19:30:15
本文介绍了使用 strtok_r 时出现分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

谁能解释为什么我在以下示例中遇到分段错误?

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 ", 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 ", 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

本文发布于:2023-11-27 02:52:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1636265.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:strtok

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!