简体   繁体   English

为什么我的 c 程序将字符串拆分为标记什么都不打印

[英]why my c program to split string into tokens prints nothing

I have code in C for splitting a sample string into tokens using the strtok() function.我在 C 中有代码,用于使用strtok()函数将示例字符串拆分为标记。 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) .我似乎已经遵循了本书的所有内容,但我的 CLion 编译器不会打印单个字符串标记并使用此代码退出脚本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);
    }

The function strtok will write null characters into the string pointed to by its first argument.函数strtok会将空字符写入其第一个参数指向的字符串中。 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.这样, sentence将是一个可写数组,而不是指向字符串文字的指针。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM