c - 传递 char* 作为参数会破坏程序,而 char[] 不会

标签 c pointers char

我有以下代码来按标记分割字符串:

char **strToWordArray(char *str, const char *delimiter)
{
  char **words;
  int nwords = 1;
  words = malloc(sizeof(*words) * (nwords + 1));

  int w = 0;
  int len = strlen(delimiter);
  words[w++] = str;
  while (*str)
  {
    if (strncmp(str, delimiter, len) == 0)
    {
      for (int i = 0; i < len; i++)
      {
        *(str++) = 0;
      }
      if (*str != 0) {
        nwords++;
        char **tmp = realloc(words, sizeof(*words) * (nwords + 1));
        words = tmp;
        words[w++] = str;
      } else {
          str--;
      }
    }
    str++;
  }
  words[w] = NULL;
  return words;
}

如果我这样做:

char str[] = "abc/def/foo/bar";
char **words=strToWordArray(str,"/"); 

那么程序就可以正常工作,但如果我这样做:

char *str = "abc/def/foo/bar";
char **words=strToWordArray(str,"/");

然后我遇到了段错误。

这是为什么呢?该程序预计 char*作为一个论点,为什么 char*参数使程序崩溃?

最佳答案

因为该函数包含:

    *(str++) = 0;

它修改传递给它的字符串。当你这样做时:

char *str = "abc/def/foo/bar";

str 指向只读字符串文字。请参阅此问题中标题为尝试修改字符串文字的部分:

Definitive List of Common Reasons for Segmentation Faults

关于c - 传递 char* 作为参数会破坏程序,而 char[] 不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45852135/

相关文章:

c - 我的 C 代码有问题,但我看不到错误。这是一个简单的程序

C宏gsl库代码转换为D

c - 使用偏移量取消引用多级指针的最简洁方法是什么?

c - C 语言中的 if (!string) 是什么意思

与字符数组连接的 C++ 字符串

c - 如何在 C 中以可移植的方式管理内存对齐和通用指针算术?

将C函数转换为Lua函数

c++ - 试图创建一个指向动态分配的 char 数组的指针

c - char 数据类型中的撇号

c++ - 如何将 char* 分配给 char 数组?