写入c-string

Mar*_*tin 3 c kr-c c-strings cstring segmentation-fault

我的代码段错误,我不知道为什么.

 1  #include <stdio.h>
 2
 3  void overwrite(char str[], char x) {
 4    int i;
 5    for (i = 0; str[i] != '\0'; i++)
 6      str[i] = x;
 7  }
 8
 9  int main(void) {
10    char *s = "abcde";
11    char x = 'X';
12    overwrite(s, x);
13    printf("%s\n", s);
14    return 0;
15  }
Run Code Online (Sandbox Code Playgroud)

gdb调试器告诉我,问题出在第6行,我想将一个char存储到c-string中(如果我使用左值指针解除引用,那就是同样的问题.)这就是他所说的:

(gdb) run
Starting program: /tmp/x/x 

Breakpoint 1, overwrite (str=0x8048500 "abcde", x=88 'X') at x.c:5
5         for (i = 0; str[i] != '\0'; i++)
(gdb) s
6           str[i] = x;
(gdb) 

Program received signal SIGSEGV, Segmentation fault.
0x080483e3 in overwrite (str=0x8048500 "abcde", x=88 'X') at x.c:6
6           str[i] = x;
(gdb) q
Run Code Online (Sandbox Code Playgroud)

我正在学习K&R-C的书,这是第2.8章(删除功能)的简化示例.我不知道问题出在哪里.

not*_*row 17

因为char*s ="abcde"; 在只读内存中创建字符串.尝试

char s[] = "abcde";
Run Code Online (Sandbox Code Playgroud)

编辑:解释:char*是指针,"abcde"在只读内存中创建 - >不可变.

char []是数组,它完全存储在堆栈中并从内存中初始化,因此是可变的