作者:路边一烧饼 | 来源:互联网 | 2023-07-19 12:05
PossibleDuplicate:strtokwontaccept:char*str可能的副本:strtok不能接受:char*strWhenusingthe
Possible Duplicate:
strtok wont accept: char *str
可能的副本:strtok不能接受:char *str
When using the strtok
function, using a char *
instead of a char []
results in a segmentation fault.
使用strtok函数时,使用char *而不是char[]会导致分割错误。
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?
谁能解释这种行为差异的原因吗?
6 个解决方案
26
char string[] = "hello world";
This line initializes string
to be a big-enough array of characters (in this case char[12]
). It copies those characters into your local array as though you had written out
这一行将字符串初始化为足够大的字符数组(在本例中为char[12])。它将这些字符复制到本地数组中,就像您编写的那样
char 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 to const char*
, but never convert it to a char*
.
C之所以允许这样的原因,主要是为了让古老的代码继续编译。您应该假定您的源代码中的字符串文字的类型是const char[],它可以转换为const char*,但永远不要将它转换为char*。