【问题标题】:Converting char* to lower case throws segfault error [duplicate]将 char* 转换为小写会引发段错误 [重复]
【发布时间】:2012-07-19 05:07:38
【问题描述】:

可能重复:
Is it possible to modify a string of char in C?

我有一个函数可以将 char* 转换为小写。这是函数:

void toLower(char* word, int length)
{
    int i;

    for(i = 0; i < length; i++) {
        // this I can do
        // printf("%c", tolower(word[i]));

        // this throws segfault
        word[i] = tolower(word[i]);
    }
}

当我从 main 中这样调用它时,它会引发段错误:

char* needle = "foobar";
toLower(needle, strlen(needle));

我确定问题出在这里的作业中:

word[i] = tolower(word[i]);

但我似乎无法找出正确的方法。我尝试将其传递为char**,或传递*(word+i),但都导致相同的问题。

【问题讨论】:

    标签: c pointers char


    【解决方案1】:

    您正在尝试更改常量字符串"foobar"。试试:

    char needle[] = "foobar";
    

    这将创建一个包含字符串"foobar"数组(编译器会安排将数据从常量字符串"foobar" 复制到您可以修改的数组needle)。

    【讨论】:

      【解决方案2】:

      您不能修改字符串文字。您可以创建一个动态字符串:

      char *str = strdup(needle);
      toLower(str, strlen(str));
      /* ... */
      free(str);
      

      【讨论】:

        【解决方案3】:

        问题在于char *needle = "foobar" 是一个字符串文字——它是一个常量字符。为了让编译器生成可写字符串,请使用

        char needle[] = "foobar";
        

        改为。

        【讨论】:

          【解决方案4】:

          无法更改字符串文字。
          你可以这样做

           word[i] = tolower(word[i]);
          

          只有两种情况

          char needle[] = "foobar";
          


          首先使用 malloc 为 char * 创建内存,然后为其分配一个字符串,如下所示

          char * str = (char *) malloc(size0f(char)*10);
          strcpy(str,"foobar");
          

          现在你可以使用它了

          【讨论】:

            猜你喜欢
            • 2011-02-23
            • 1970-01-01
            • 2022-01-10
            • 2021-11-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-07-03
            • 1970-01-01
            相关资源
            最近更新 更多