函数strtok不会接受:字符*海峡 [英] strtok wont accept: char *str

查看:139
本文介绍了函数strtok不会接受:字符*海峡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用的char * str作为第一个参数(不是分隔符字符串)时的strtok不会正常工作。

这是否有东西做,在这符号串分配的区域? (这是据我所知,是一个只读区域)。

在此先感谢

例如:

  //字符*海峡= - 这,样本串。 //< ---不工作
烧焦海峡[] = - 这,样本串; //< ---作品
CHAR delims [] =;
字符* PCH;
的printf(分割字符串\\%s \\的成标记:\\ n,STR);
PCH = strtok的(STR,delims);
而(PCH!= NULL)
{
  的printf(%S \\ n,PCH);
  PCH =的strtok(NULL,delims);
}
返回0;


解决方案

在第一种情况下,你传递一个字符串函数strtok()。由于的strtok()修改此字符串,并作为字符串不能合法进行修改,你最终未定义行为。在第二种情况下,编译器的副本串入的阵列。数组内容可以修改,所以这code是确定。

strtok wont work correctly when using char *str as the first parameter (not the delimiters string).

Does it have something to do with the area that allocates strings in that notation? (which as far as i know, is a read-only area).

thanks in advance

example:

//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;

解决方案

In the first case, you pass a string literal to strtok(). As strtok() modifies this string, and as string literals cannot legally be modified, you end up with undefined behaviour. In the second case, the compiler copies the string into the array. Array contents can be modified, so this code is OK.

这篇关于函数strtok不会接受:字符*海峡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆