本文链接:http://blog.csdn.net/ncepuwanghui/article/details/23713253
#include <iostream>
using namespace std;
int main(int argc, const char* argv[])
{
//char *p1 = "Hello";//错误写法,会产生警告
/* 常量指针:
* 本身是一个指针,一个指向常量的指针,是变量
* 常量指针可以指向其他地址,但是所指地址单元的内容不能修改
* 常用来作函数形参,以保护实参不会被非法修改
*/
const char *p1 = "Hello";//正确写法=char const *p1 = "Hello";
cout << "p1 = " << (void*)p1 << endl;//字符串"Hello"存放的单元地址
cout << "*p1 = " << p1 << endl;//指针ptr所指单元内容
//cout << "*p1 = " << *p1 << endl;//只会打印'H'
//*p1 = 'h';//错误用法,不能修改p1所指地址单元的内容
p1 = "World";
cout << "p1 = " << (void*)p1 << endl;
cout << "*p1 = " << p1 << endl;
cout << "================================================" << endl;
/* 指针常量:
* 本身是一个常量,一个指针类型的常量
* 指针所指地址一旦初始化就不能修改,但是指针所指地址单元的内容可以修改
*/
char *q1 = new char('H');
char * const p2 = q1;
cout << "p2 = " << (void*)p2 << endl;
cout << "*p2 = " << p2 << endl;
*p2 = 'h';
cout << "p2 = " << (void*)p2 << endl;
cout << "*p2 = " << p2 << endl;
char *q2 = new char('W');
/*p2 = q2;//指针p2是常量,初始化后无法在修改
*cout << "p2 = " << (void*)p2 << endl;
*cout << "*p2 = " << p2 << endl;
*/
return 0;
}