【问题标题】:Differences between array and pointer string declaration数组和指针字符串声明的区别
【发布时间】: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


【解决方案1】:

来自strtok()man page

使用这些功能时要小心。如果您确实使用它们,请注意:

  • 这些函数修改它们的第一个参数。

  • 这些函数不能用于常量字符串。

作为您的代码,str 保存静态分配的字符串字面量的基地址,通常只读

在你的代码中,改变

char *str = (char *)malloc(1000*sizeof(char));
str ="- This, a sample string.";

char *str = malloc(1000);
strcpy(str, "- This, a sample string.");

此外,首先使用malloc() 将内存分配给str,然后分配字符串文字给str覆盖由@987654330 返回的先前分配的内存@,导致内存泄漏。

接下来,

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

这很好用,因为您在此处初始化一个本地array,并且它的包含可修改

注意:

do not castmalloc()的返回值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-19
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-20
    • 2013-12-16
    • 2019-03-01
    相关资源
    最近更新 更多