为什么我的C程序将字符串分为令牌没有打印

发布于 2025-02-10 03:42:16 字数 573 浏览 0 评论 0原文

我在C中使用strtok()函数将示例字符串分配到令牌中。我似乎已经遵循了本书的所有内容,但是我的Clion编译器没有打印单个字符串令牌,并使用此代码在带有退出代码的过程-1073741819(0xc000000005)中退出脚本。以下是我试图拆分字符串的方式,请帮助我调试问题。

//declare and assign the sentence I need to split
char * sentence ="Cat,Dog,Lion";
//declare and assign the delimiter 
char * delim=",";
//get the first token
char * token = strtok(sentence, delim);
while(token!= NULL){
     //print a single string token
      printf("%s",token);
      //reset the loop for the iteration to continue
      token = strtok(NULL,delim);
    }

I have code in C for splitting a sample string into tokens using the strtok() function. I seem to have followed everything by the book but my CLion compiler does not print the individual string tokens and exits the script with this code Process finished with exit code -1073741819 (0xC0000005). Below is how I am trying to split the string, help me debug the issue.

//declare and assign the sentence I need to split
char * sentence ="Cat,Dog,Lion";
//declare and assign the delimiter 
char * delim=",";
//get the first token
char * token = strtok(sentence, delim);
while(token!= NULL){
     //print a single string token
      printf("%s",token);
      //reset the loop for the iteration to continue
      token = strtok(NULL,delim);
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

韬韬不绝 2025-02-17 03:42:16

函数 strtok 将写入null字符进入字符串,指向其第一个参数。因此,该字符串必须是可写的。但是,您正在提供A string flital ,仅读取。试图写入字符串文字将调用 undefined行为

因此,解决问题的最简单解决方案是将行更改

char * sentence ="Cat,Dog,Lion";

为:

char sentence[] = "Cat,Dog,Lion";

这样,句子将是一个可写的数组,而不是指向字符串文字的指针。

The function strtok will write null characters into the string pointed to by its first argument. Therefore, that string must be writable. However, you are supplying a string literal, which is read-only. Attempting to write to a string literal will invoke undefined behavior.

The simplest fix to your problem would therefore be to change the line

char * sentence ="Cat,Dog,Lion";

to:

char sentence[] = "Cat,Dog,Lion";

That way, sentence will be a writable array, instead of a pointer to a string literal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文