V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
thomaswang
V2EX  ›  问与答

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

  •  
  •   thomaswang · 2018-03-22 21:18:15 +08:00 · 1326 次点击
    这是一个创建于 2198 天前的主题,其中的信息可能已经有所发展或是发生改变。
      char *name = "abc";
      printf("%c\n", name[1]);
      printf("%c\n", *(name + 1));
      *(name + 1) = 'B';
    

    结果:

    b
    b
    Bus error: 10
    

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

    11 条回复    2018-05-22 18:09:20 +08:00
    pkookp8
        1
    pkookp8  
       2018-03-22 21:19:28 +08:00 via Android
    abc 在字符常量区,了解一下
    ShadowStar
        2
    ShadowStar  
       2018-03-22 21:23:48 +08:00
    char name[] = "abc";
    thomaswang
        3
    thomaswang  
    OP
       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
        4
    thomaswang  
    OP
       2018-03-22 21:26:52 +08:00
    结果:
    b
    b
    aAc

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

    ``` c

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

    ```
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1170 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 23:04 · PVG 07:04 · LAX 16:04 · JFK 19:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.