C/C++里的const(1)

首先来看这样一段程序:

 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     char *s = "hello world";
 5 
 6     cout << s << endl;
 7     s[0] = 'B';
 8     cout << s << endl;
 9     return 0;
10 }

在VS2013下编译运行的结果是:

什么原因呢?

计算机中的内存在用于编程时,被进行了分区(Segment),分为:“栈区”(Stack)、“堆区”(Heap)、全局区(静态区,Static )、文字常量区和代码区。

使用*s定义的字符串存储在文字常量区内,这一部分是默认为为const类型的,因此不能修改。

当把程序改成如下,就可以得到想要的效果了。

 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     //char *s = "hello world";
 5     char s[] = "hellow world";
 6     cout << s << endl;
 7     s[0] = 'B';
 8     cout << s << endl;
 9     while (1);
10     return 0;
11 }

运行结果:

通过打印一下两种方式的字符串首地址,跟容易发现问题所在。

修改后的程序:

 1 #include<iostream>
 2 using namespace std;
 3 int main(){
 4     char *s1 = "hello world";
 5     char s2[] = "hellow world";
 6     cout << &s1 << endl;
 7     //s[0] = 'B';
 8     cout << &s2 << endl;
 9     cout << &main << endl;
10     while (1);
11     return 0;
12 }

运行结果:

可以发现由字符串定义的字符串被放到了很靠前的地址空间(栈区);而由指针定义的字符串与main函数地址很近。

原文地址:https://www.cnblogs.com/jacklu/p/4394639.html