zoukankan      html  css  js  c++  java
  • [c++基础] const char and static const char

    部分内容摘自:https://blog.csdn.net/ranhui_xia/article/details/32696669

    The version with const char * will copy data from a read-only location to a variable on the stack.

    The version with static const char * references the data in the read-only location (no copy is performed).

    在函数内部,const char *每次调用函数时,都需要在stack上分配内存,然后将数据拷贝过来,函数退出前释放。

    而static const char *,会直接访问read only的数据,无需再stack上分配内存。

    char * const cp     : 定义一个指向字符的指针常数,即const指针

    const char* p       : 定义一个指向字符常数的指针

    char const* p       : 等同于const char* p

    举个例子:

     1 #include <iostream>
     2 #include <cstdio>
     3 using namespace std;
     4 
     5 int main()
     6 {
     7     char ch[3] = {'a','b','c'};
     8     char* const cp = ch;
     9     printf("char* const cp: 
     %c
    ", *cp);
    10     /* 
    11     ** cp point to a fixed address
    12     **
    13     cp++;  //error: increment of read-only variable ‘cp’
    14     printf("char* const cp: 
     %c
    ", *cp);
    15     **
    16     */
    17 
    18     const char ca = 'a';
    19     const char* p1 = &ca;
    20 
    21     /* 
    22     ** 2. Only const char* pointer can point to a const char
    23     **
    24     const char cb = 'b';
    25     char* p2 = &cb; //error: invalid conversion from ‘const char*’ to ‘char*’
    26     **
    27     **/
    28 
    29     /*
    30     ** 3. p1 points to a const char, the char be pointed has to be const, 
    31     **    p1 can point to a different const char
    32     */ 
    33     printf("const char* p1: 
     %c
    ", *p1);
    34     const char cb = 'b';
    35     p1 = &cb;
    36     printf(" %c
    ", *p1);
    37     return 0;
    38 }
    39 
    40 /*
    41 ** Output:
    42 char* const cp: 
    43  a
    44 const char* p1: 
    45  a
    46  b
    47 **
    48 */

  • 相关阅读:
    读书笔记_Effective_C++_条款三十一:将文件间的编译依存关系降至最低(第三部分)
    Spring Boot进阶系列一
    职场进阶之七种武器
    大龄IT程序员的救赎之道
    Web Service
    生产者消费者问题
    SpringBoot集成Apache Shiro
    简单模拟医院叫号系统
    IT小团队管理者的突围之道
    内部推荐
  • 原文地址:https://www.cnblogs.com/shiyublog/p/9757038.html
Copyright © 2011-2022 走看看