且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

函数strtok造成段错误,但不是在通过code步骤

更新时间:2021-09-01 00:32:21

的strtok()函数修改,你要分析,并更换所有的分隔符字符串 \\ 0 NUL符号。

The strtok() function modifies string that you wants to parse, and replace all delimiters with \0 nul symbol.

阅读:的char * strtok的(字符*海峡,为const char *分隔符);

海峡结果
   C字符串截断。结果
   注意,这个字符串的内容
  被修改并分解成较小的字符串(令牌)
。 Alternativelly,
  空指针可以指定,在这种情况下,功能继续
  扫描其中previous成功调用该函数结束了。

str
C string to truncate.
Notice that the contents of this string are modified and broken into smaller strings (tokens). Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.

在您的code:

 strtok(dateString, " "); 
           ^
           |  is a constant string literal 

dateString 2011年4月16日00:00一个常量字符串,并且通过使用的strtok()您code试图写只读存储器 - 这是非法的,这引起了分段错误。

dateString points to "2011/04/16 00:00" a constant string literal, and by using strtok() your code trying to write on read-only memory - that is illegal and this caused segmentation fault.

阅读linked答案图了解:如何的strtok()作品?

Read this linked answer for diagram to understand: how strtok() works?

编辑:

@: 的char * strtok的(字符*海峡,为const char *分隔符); 在给定的code例如, STR 是一个数组,而不是常量字符串。它的声明:

@: char * strtok ( char * str, const char * delimiters ); In given code example, str is an array, not constant string literal. Its declaration:

char str[] ="- This, a sample string.";

下面海峡[] 被终止的字符数组的NUL,与字符串初始化其长度等于指定字符串的大小。您可以更改的海峡[] 例如内容海峡[I] ='A'是一个有效的操作。

Here str[] is an nul terminated array of chars, that initialized with string and its length is equals to size of the assigned string. You can change the content of str[] e.g. str[i] = 'A' is a valid operation.

而在你的code:

char * dateTimeString = "2011/04/16 00:00"; 

dateTimeString 是指向字符串是不可修改的如 dateTimeString [I] ='A'是一个非法操作这个时候。

dateTimeString is pointer to string literal that is not modifiable e.g dateTimeString[i] = 'A' is an illegal operation this time.