浅析字符常量区

来源:互联网 发布:对象转json忽略null 编辑:程序博客网 时间:2024/05/22 17:35

以下程序编译环境为gcc

1.

#include <stdio.h>#include <string.h>int main(){char* s1 = "Hello";s1[0] = 'z';printf("%s\n",s1);return 0;}

编译不会出错,但运行错误Segmentation fault。因为字符串"Hello"在字符常量区,指针s1指向字符常量区,字符常量区是不可更改的,所以(s1[0] = 'z') 这一步错误。
其实,char* s1 = "Hello" 等价于 const char* s1 = "Hello" 
2.
#include <stdio.h>#include <string.h>int main(){char s2[] = "world";s2[0] = 'z';printf("%s\n",s2);return 0;}
这段程序运行正确。字符串"world"存储在数组s2里,在栈空间中,可以进行修改。



原创粉丝点击