zoukankan      html  css  js  c++  java
  • 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函数地址很近。

  • 相关阅读:
    线程池的爆掉
    WebApi的调用-1.前端调用
    使用SqlSugar 4.X的T4生成实体类
    JSON.NET 空值处理, 数字转字符,时间格式化
    C#获取路径
    MVC4 下DropDownList使用方法(转)
    14.并发与异步
    14.并发与异步
    14.并发与异步
    VS2013 生成时复制文件或目录到指定目录
  • 原文地址:https://www.cnblogs.com/jacklu/p/4394639.html
Copyright © 2011-2022 走看看