thomaswang
V2EX  ›  问与答

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

  •  
  •   thomaswang · Mar 22, 2018 · 2281 views
    This topic created in 3171 days ago, the information mentioned may be changed or developed.
      char *name = "abc";
      printf("%c\n", name[1]);
      printf("%c\n", *(name + 1));
      *(name + 1) = 'B';
    

    结果:

    b
    b
    Bus error: 10
    

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

    11 replies  •  2018-05-22 18:09:20 +08:00
    pkookp8
    pkookp8
    Mar 22, 2018 via Android
    1
    abc 在字符常量区,了解一下
    ShadowStar
    ShadowStar
    Mar 22, 2018
    2
    char name[] = "abc";
    thomaswang
    thomaswang
    OP
    Mar 22, 2018
    3
    @pkookp8
    @ShadowStar
    ```
    char name2[] = "abc";
    printf("%c\n", name2[1]);
    printf("%c\n", *(name2 + 1));
    name2[1] = 'A';
    printf("%s\n", name2);

    ```
    thomaswang
    thomaswang
    OP
    Mar 22, 2018
    4
    结果:
    b
    b
    aAc

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

    ``` c

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

    ```
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   3470 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 04:05 · PVG 12:05 · LAX 20:05 · JFK 23:05
    ♥ Do have faith in what you're doing.