【发布时间】:2014-12-11 09:41:32
【问题描述】:
我正在拆分字符串。
当我运行这段代码时,我遇到了一个错误(MacO 上的 Bus error: 10 或 Linux 上的 SegFault)。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char *str = (char *)malloc(1000*sizeof(char));
str ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}
当我将 str 声明更改为 char str[] ="- This, a sample string."; 时,它运行良好。
谁能告诉我为什么?我的大脑正在融化。
【问题讨论】:
-
如果不使用它的返回值,为什么要调用
malloc? -
这是一个简单的例子,真实的东西需要返回一个值。
-
请省略示例中的冗余代码。他们只是令人困惑。
标签: c pointers segmentation-fault strtok