1、常量指针
const char *str(常量指针)
意思是str指向内存的内容不能通过str来修改,用来保护str指向内存的内容。
但是,str的指向是可以改变的。
#include <stdio.h>
int main()
{
char buf[20]="hello world";
const char *str=buf;
printf("str=%s\n",str);
//*str='w';[Error] assignment of read-only location '*str'
//str指向的位置是只读的,不能被分配。
str="hello kitty";
printf("str=%s\n",str);
return 0;
//str=hello world
//str=hello kitty
}
2、指针常量
char* const str(指针常量)
str是只读的变量,str不能指向别的地方
但是,str指向的内存的内容是可以被修改的。
#include <stdio.h>
int main()
{
char buf[20]="hello world";
char* const str=buf;
printf("str=%s\n",str);
//str="hello kitty";[Error] assignment of read-only variable 'str'
//str是只读的不能被修改。
*str='w';
printf("str=%s\n",str);
return 0;
//str=hello world
//str=wello world
}
3、指针常量+常量指针
const char* const str
str不能指向别的地方,指向的内存的内容也不能通过str去修改。
#include <stdio.h>
int main()
{
char buf[20]="hello world";
const char* const str=buf;
printf("str=%s\n",str);
return 0;
//*str='w'; [Error] assignment of read-only location '*str'
//str="hello kitty";[Error] assignment of read-only variable 'str'
}