c语言const的用处之一
// xxx.cpp : Defines the entry point for the console application. // #include "stdafx.h" #define mp printf int main(int argc, char* argv[]) { char * p1 = "12345"; //相当于【指针常量】:指向的是常量,12345不能修改。 char temp[5]; char * const p2 = temp; //【常量指针】:地址不能变,temp数组内容可以修改。 //*p1='\0'; //如果这样处理内存,就会非常危险,所以报内存不可写,所以我说相当于。。。。【指针常量】 //*p2='\0'; //这样处理内存很正常,应为设置了正确的缓存区。 //p2="ttttt"; //指针常量 地址不能变啊,编译期就报错了。 //p1="ttttt"; //【指针常量】和指针一样,自身的地址随便改。没问题。 char const * const p3 ="12345"; //这个就厉害了,地址和指向的内容都不能改。就叫他【常量指针常量】 //p3="ttttt"; //不行 //*p3='\0'; //不行 编译就报错,const保护了系统内存,避免内存只读的异常产生。 mp("%s",p2); return 0; }