c - strtok 不会接受 : char *str

标签 c string strtok

当使用 char *str 作为第一个参数(不是分隔符字符串)时,strtok 将无法正常工作。

是否与分配字符串的区域有关? (据我所知,这是一个只读区域)。

提前致谢

例子:

//char* str ="- This, a sample string.";   // <---doesn't work
char str[] ="- This, a sample string.";   // <---works
char delims[] = " ";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str,delims);
while (pch != NULL)
{
  printf ("%s\n",pch);
  pch = strtok (NULL, delims);
}
return 0;

最佳答案

在第一种情况下,您将字符串文字传递给 strtok()。由于 strtok() 修改了此字符串,并且由于无法合法修改字符串文字,因此您最终会遇到未定义的行为。在第二种情况下,编译器将字符串复制到数组中。数组内容可以修改,所以这段代码是可以的。

关于c - strtok 不会接受 : char *str,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2529834/

相关文章:

c - 切换小程序不让我输入选项

c - cvAddWeighted针对不同尺寸的图像

Android alsa snd_pcm_open default no such file o 目录

在 C 中将 char * 转换为大写

c - 使用 strtok() 定界路径

c - strtok 无法标记化?

c - Memcpy 拷贝比预期多

php - 如何将退格字符添加到字符串文字?

JavaScript split() join() 仅适用于精确短语

php - 剪切(裁剪)字符串中的一些文本