900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > [c++基础] const char and static const char

[c++基础] const char and static const char

时间:2019-09-06 10:46:27

相关推荐

[c++基础] const char and static const char

部分内容摘自:/ranhui_xia/article/details/32696669

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

The version withstatic 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 { 7char ch[3] = {'a','b','c'}; 8char* const cp = ch; 9printf("char* const cp: \n %c\n", *cp);10/* 11** cp point to a fixed address12**13cp++; //error: increment of read-only variable ‘cp’14printf("char* const cp: \n %c\n", *cp);15**16*/17 18const char ca = 'a';19const char* p1 = &ca;20 21/* 22** 2. Only const char* pointer can point to a const char23**24const char cb = 'b';25char* 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 char32*/ 33printf("const char* p1: \n %c\n", *p1);34const char cb = 'b';35p1 = &cb;36printf(" %c\n", *p1);37return 0;38 }39 40 /*41 ** Output:42 char* const cp: 43 a44 const char* p1: 45 a46 b47 **48 */

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。