编译器不允许我编辑传递的字符串

标签 c string segmentation-fault string-literals

我环顾四周,在其他问题中找不到我的问题的解决方案。由于某种原因,当我运行程序时出现段错误,这似乎是因为我正在更改给定的字符串。我尝试将指针传递给 char 指针并对其进行编辑,但无济于事。

我得到什么:

之前:胡安巴布罗 段错误(核心转储)

我的代码:

void rm_char(char* word, int pos){

   printf("before: %s\n", word);

   int len = strlen(word);

   int i;

   i = pos;

   while(word[i+1] != '\0'){

     word[i] = word[i+1];

     i++;
   } 

   word[i] = '\0';

   printf("after: %s\n", word);
} 


int main(void){

   rm_char("juanpablo", 2);

}

最佳答案

来自 C 标准(6.4.5 字符串文字)

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

要避免错误,您可以调用如下函数

char s[] = "juanpablo";   

rm_char( s, 2 );

考虑到第二个参数最好使用 size_t 类型而不是 int 类型,并且声明的变量 len 如下

int len = strlen(word);

未在函数中使用。

函数应该这样声明

char * rm_char(char* word, size_t pos);

这是一个演示程序

#include <stdio.h>
#include <string.h>

char * rm_char(char *word, size_t pos)
{
    size_t n = strlen( word );

    if ( pos < n )
    {
        //memmove( word + pos, word + pos + 1, n - pos );
        do 
        {
            word[pos] = word[pos+1];
        } while ( word[pos++] );
    }

    return word;
}

int main(void) 
{
    char word[] = "juanpablo";

    puts( word );
    puts( rm_char( word, 2 ) );

    return 0;
}

它的输出是

juanpablo
junpablo

关于编译器不允许我编辑传递的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47681043/

相关文章:

string - 在Lua中提取字符串的最后N个字符?

php - 如何从 php 中包含 '<' 符号的字符串中删除空格?

c - 尝试使用 git_clone 函数导致段错误

c - 使用指针而不是数组时出现段错误

Emacs 可以告诉我调用特定函数的位置吗?

c - 如何在 c 中使用 Winrt API 创建库?

javascript - 如何替换JS字符串中的所有\"?

c - 为什么在写入使用字符串文字初始化的 "char *s"而不是 "char s[]"时出现段错误?

c - 为什么 math.h 不定义倒数三角函数?

c - 如何在c中从char*访问char[]?