通过指针改变字符数组的值

2018-03-22 21:18:15 +08:00
 thomaswang
  char *name = "abc";
  printf("%c\n", name[1]);
  printf("%c\n", *(name + 1));
  *(name + 1) = 'B';

结果:

b
b
Bus error: 10

我想把 b -> B 这样操作为啥不行,应该怎么做呢

1335 次点击
所在节点    问与答
11 条回复
pkookp8
2018-03-22 21:19:28 +08:00
abc 在字符常量区,了解一下
ShadowStar
2018-03-22 21:23:48 +08:00
char name[] = "abc";
thomaswang
2018-03-22 21:26:13 +08:00
@pkookp8
@ShadowStar
```
char name2[] = "abc";
printf("%c\n", name2[1]);
printf("%c\n", *(name2 + 1));
name2[1] = 'A';
printf("%s\n", name2);

```
thomaswang
2018-03-22 21:26:52 +08:00
结果:
b
b
aAc

这样就是可以的, 为什么呢
des
2018-03-22 21:32:27 +08:00
@thomaswang 一楼已经说过了
pkookp8
2018-03-22 21:34:14 +08:00
@thomaswang 前者存在字符常量区,抄袭的时候就确定了,你可以打开编译后的二进制文件搜索 abc,改了再运行打出来。指针指向字符常量区的地址是不可改变的,只读区域,除非能把内存里加载的二进制文件改了。后者是数组,abc 从常量区压入了栈,栈是一块可读写的区域。栈由系统自动申请释放。
希望没说错
pkookp8
2018-03-22 21:34:41 +08:00
@pkookp8 抄袭->编译
roychan
2018-03-22 21:37:56 +08:00
char* 出来的字符串在 .text 里,只读。而 char[] 出来的在 stack 上,可读可写。
liuminghao233
2018-03-22 21:39:31 +08:00
const 的东西怎么改
thomaswang
2018-05-22 18:08:22 +08:00
```
char *name1 = "zhangsan";
char name2 = "zhangsan";
```
它们最根本的区别是在内存中的存储区域不一样,字符数组存储在全局数据区或栈区,第二种形式的字符串存储在常量区。全局数据区和栈区的字符串(也包括其他数据)有读取和写入的权限,而常量区的字符串(也包括其他数据)只有读取权限,没有写入权限。
thomaswang
2018-05-22 18:09:20 +08:00
@thomaswang

``` c

char *name1 = "zhangsan";
char name2 = "zhangsan";

```

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/440569

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX