简体   繁体   English

当字符串是char *时,strtok_s崩溃程序

[英]strtok_s crashes program when string is of char *

I am trying to get a token from a string that is delimited by space(" "). 我试图从一个由空格(“”)分隔的字符串中获取一个标记。 But the following code crashes the application when the string is of char * type. 但是当字符串是char *类型时,以下代码会崩溃应用程序。

#include <stdio.h>
#include <string.h>

int main(){

char *str1 = "Hello World!"; //char str1[] works
char *token;
char *savePtr;

token = strtok_s(str1, " ", &savePtr);

printf("%s", token);

return 0;
}

I also get the following warnings: 我还收到以下警告:

C:\Users\Haris\Desktop\C files>gcc firstProgram.c -o firstprogram.exe
firstProgram.c: In function 'main':
firstProgram.c:10:9: warning: implicit declaration of function 'strtok_s' [-Wimplicit-function-declaration]
 token = strtok_s(str1, " ", &savePtr);
         ^
firstProgram.c:10:7: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
 token = strtok_s(str1, " ", &savePtr);

The strtok_s function modifies the thing the pointer points to, turning delimiters into zeroes. strtok_s函数修改指针指向的东西,将分隔符转换为零。 So it cannot take a pointer to a constant. 所以它不能指向常量。 But you pass it str1 , which is a pointer to a string constant. 但是你传递str1 ,它是一个指向字符串常量的指针。 When it tries to modify that string to turn the delimiters into zeroes, it tries to modify a constant. 当它尝试修改该字符串以将分隔符转换为零时,它会尝试修改常量。 That is, of course, illegal. 那当然是非法的。

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

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