为什么我的C程序将字符串分为令牌没有打印
我在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
函数
strtok
将写入null字符进入字符串,指向其第一个参数。因此,该字符串必须是可写的。但是,您正在提供A string flital ,仅读取。试图写入字符串文字将调用 undefined行为。因此,解决问题的最简单解决方案是将行更改
为:
这样,
句子
将是一个可写的数组,而不是指向字符串文字的指针。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
to:
That way,
sentence
will be a writable array, instead of a pointer to a string literal.