字符串常量&段错误

来源:互联网 发布:网络视频服务器使用 编辑:程序博客网 时间:2024/04/30 19:53
#include<stdio.h>
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

0 0
原创粉丝点击