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 */

  • 相关阅读:
    Java 语句总结
    存储过程 替换字符串
    解决MyEclipse吃内存以及卡死的方法
    Tomcat启动时自动加载一个类
    oracle sql日期比较:
    项目数据库操作
    Oracle 删除重复数据只留一条
    oracle ORA-00001:违反唯一约束条件
    Oracle ORA-12519: TNS:no appropriate service handler found 解决
    tomecat 配置修改 及启动配置
  • 原文地址:https://www.cnblogs.com/shiyublog/p/9757038.html
Copyright © 2011-2022 走看看