thomaswang
V2EX  ›  问与答

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

  •  
  •   thomaswang · Mar 22, 2018 · 1958 views
    This topic created in 3022 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
        1
    pkookp8  
       Mar 22, 2018 via Android
    abc 在字符常量区,了解一下
    ShadowStar
        2
    ShadowStar  
       Mar 22, 2018
    char name[] = "abc";
    thomaswang
        3
    thomaswang  
    OP
       Mar 22, 2018
    @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
       Mar 22, 2018
    结果:
    b
    b
    aAc

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

    ``` c

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

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