写入 c 字符串 [英] Writing into c-string
问题描述
我的代码段错误,我不知道为什么.
my code segfaults and I don't know why.
1 #include <stdio.h>
2
3 void overwrite(char str[], char x) {
4 int i;
5 for (i = 0; str[i] != ' '; 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
", s);
14 return 0;
15 }
gdb 调试器告诉我,问题出在第 6 行,我想将一个 char 存储到 c-string 中(如果我使用左值指针解引用,这是同样的问题.)这是他所说的:
The gdb debugger tells me, that problem is on the line 6, where I want to store a char, into c-string (if I use lvalue pointer dereferencing, it's the same problem.) This is what he says:
(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] != ' '; 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
我正在从 K&R-C 书中学习,这是第 2.8 章中的简化示例(删除功能).我不知道问题出在哪里.
I am learning from K&R-C book and this is simplified example from chapter 2.8 (the remove function). I have no idea where is the problem.
推荐答案
因为 char*s = "abcde";在只读内存中创建字符串.试试
because char*s = "abcde"; creates string in readonly memory. try
char s[] = "abcde";
解释:char* 是指针,abcde"是在只读内存中创建的 -> 不可变.
explanation: char* is pointer, and "abcde" is created in readonly memory -> immutable.
char[]是数组,完全存放在栈上,从内存中初始化,所以是可变的
char[] is array, which is wholly stored on stack and initialized from the memory, so is mutable
这篇关于写入 c 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!