Bjarne在他的The C++ Programming Language里面给出过一个助记的方法:
把一个声明从右向左读。
char * const cp; ( * 读成 pointer to )
cp is a const pointer to char
const char * p;
p is a pointer to const char;
======================================================================
测试代码:
- #include <stdio.h>
-
-
int main( int argc, char *argv[] )
-
{
-
char p[] = "test string";
-
-
const char * p1 = p; //p1 is a pointer to const char;
-
//*(p1 +2 ) = 'L'; // wrong, 内容是常量
-
p1 = "new test string p1"; //right,指针可以改
-
-
-
char * const p2 = p; //p2 is a const pointer to char
-
*(p2 + 2 ) = 'L'; // right , 指针是常量,内容可以修改
-
//p2 = "new test string p2"; //wrong, 指针是常量不能修改
-
-
fprintf(stdout, "p1=%s\np2=%s\n", p1, p2);
-
-
return 0;
-
}
阅读(1821) | 评论(0) | 转发(0) |