const在指针中的用法

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'
}  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值