strtok的 - 字符数组与字符指针 [英] strtok - char array versus char pointer

查看:130
本文介绍了strtok的 - 字符数组与字符指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  的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 *str

When using the strtok function, using a char * instead of a char [] 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 case char[12]). It copies those characters into your local array as though you had written out

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*.

这篇关于strtok的 - 字符数组与字符指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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