字符串常量&段错误
来源:互联网 发布:网络视频服务器使用 编辑:程序博客网 时间:2024/04/30 19:53
int main(void)
{
/*
const int a = 5;
//a = 6; // error: assignment of read-only variable ‘a’
int *p;
p = (int *)&a;// 这里报警高可以通过强制类型转换来消除
*p = 6;
printf("a = %d.\n", a);// a = 6,结果证明const类型的变量被改了
*/
const char* s = "Hello world!";
s[0] = 'L';
printf("%s\n", s);
*/
return 0;
}
上面有两段代码第一段代码中的const常量可以被改变,而第二段代码中的const常量字符串不可以被改变。在gcc编译器中运行时会报段错误。
分析其原因:字符串常量和const int a 这个整形常量在内存中存储的位置不同
字符串常量存储在文字常量区【1】,存储在这个区域的东西是只读的,操作系统不会让你去修改。
而const int a 这个整形常量存储在内存中的栈空间上,运行时栈空间上的内容是可读写的,对比看看下面这个程序中不同变量的地址就会明白了!
#include<stdio.h>
int main(void)
{
const char *p = "hello world";
char str[] = "hello world";
const int a = 0 ;
int b = 0;
printf("the adderss of hello world is%x\n",(unsigned int)p);//打印“hello world”这个字符串常量的地址
printf("the adderss of the array is%x\n",(unsigned int)str); //打印数组的地址
printf("the address of a is%x\n",(unsigned int)&a); //打印int 型常量的地址
printf("the address of b is%x\n",(unsigned int)&b);//打印int型变量的地址
return 0;
}
程序在gcc编译后运行结果:
the adderss of hello world is 80485b0
the adderss of the array is bfa82d50
the address of a is bfa82d44
the address of b is bfa82d48
后面三种类型数据地址都挨的很进存储在栈空间中,程序在运行的过程中可以读写他们所在的内存空间;
然而字符串常量hello world所在的内存空间和下面几种数据类型的变量存储的空间不同,字符串常量存储的空间在文字常量区,操作系统只允许程序运行时读这个空间而不让修改。
【1】字符串常量到底存放在哪个存储区 http://blog.csdn.net/daiyutage/article/details/8605580
- 字符串常量&段错误
- 字符串常量不能改写+段错误(ubuntu)
- c/c++ 大段字符串常量
- javascript未结束的字符串常量错误
- JS报未结束字符串常量错误
- 字符串常量赋值导致的错误
- javascript 拼接字符串遇到错误"未终止的字符串常量"
- OBJC中声明字符串常量的一个常见错误(常量指针和指针常量)
- 常量,字符串常量
- 常量错误
- 字符串常量
- 字符串常量
- 字符串常量
- 字符串常量
- 字符串常量
- 字符串常量
- 字符串常量
- 字符串常量
- Guibs 的 Python学习_字典
- Guibs 的 Python学习_While&Input
- Mac OSX上虚拟机Centos7安装virtualbox guest addtions
- CSU 1803 2016 【枚举】
- js案例-4 经典tab栏切换
- 字符串常量&段错误
- java 抽象类的应用(模板设计模式)
- Guibs 的 Python学习_ 函数
- lambda
- servlet涉及对象
- SQL语句
- gcc编译的背后
- TreeSet的comparable接口
- 2016.9.4