strtok的 - 字符数组与字符指针 [英] strtok - char array versus char pointer
问题描述
可能重复:结果
的strtok不会接受:的char * str中
块引用>在使用
strtok的
功能,使用的char *
,而不是的char [ ]
导致分段错误。这正常运行:
字符字符串[] =Hello World的;
字符*结果= strtok的(字符串,);这将导致分段错误:
的char *字符串=Hello World的;
字符*结果= strtok的(字符串,);任何人能解释是什么原因导致这种行为差异?
解决方案字符字符串[] =Hello World的;
这行初始化
字符串
是字符的大足阵列(在这种情况下,的char [12]
)。它复制这些字符到本地阵列,就像你写了字符字符串[] = {'H','E','L','L','O','','W','O',' R','L','D','\\ 0'};
其他行:
的char *字符串=Hello World的;
不初始化本地阵列,它只是初始化本地指针。编译器允许其设置为一个指向它的数组你不能更改的,就好像code组
为const char literal_string [] =Hello World的;
字符*字符串=(字符*)literal_string;的C之所以允许这种没有投主要是为了让古老的code继续汇编。你应该pretend一个字符串在源$ C $ C字面的类型是
为const char []
,它可以转换为常量字符*
,但从来没有将它转换为的char *
。Possible Duplicate:
strtok wont accept: char *strWhen using the
strtok
function, using achar *
instead of achar []
results in a segmentation fault.This runs properly:
char string[] = "hello world"; char *result = strtok(string, " ");
This causes a segmentation fault:
char *string = "hello world"; char *result = strtok(string, " ");
Can anyone explain what causes this difference in behaviour?
解决方案char string[] = "hello world";
This line initializes
string
to be a big-enough array of characters (in this casechar[12]
). It copies those characters into your local array as though you had written outchar string[] = { 'h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '\0' };
The other line:
char* string = "hello world";
does not initialize a local array, it just initializes a local pointer. The compiler is allowed to set it to a pointer to an array which you're not allowed to change, as though the code were
const char literal_string[] = "hello world"; char* string = (char*) literal_string;
The reason C allows this without a cast is mainly to let ancient code continue compiling. You should pretend that the type of a string literal in your source code is
const char[]
, which can convert toconst char*
, but never convert it to achar*
.这篇关于strtok的 - 字符数组与字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!