strcpy的参数

          strcpy我们应该是经常用的,C语言的基本函数,该函数的第一个参数是char *,第二个参数是const char *。其实关于第二参数我一直没怎么注意,这里为什么是const char *呢?我们在传这个参数的时候需不需要进行const类型强制转换,今天就遇到了。

         strcpy的第二个参数,我们平时直接传的char *,用着很好,没啥问题。那为什么用const char *,原因是const char *能接受char *,而char *却不能接受const char *。

[xxx@localhost strcpy]$ 
[xxx@localhost strcpy]$ cat fun.c 
#include<stdio.h>

void func(char *str)
{
   printf("str=%s\n",str);
}


int main()
{
   const char str1[]="abc";
   char str2[]="def";

   func(str1);
   func(str2);

   return 0;
}
[xxx@localhost strcpy]$ gcc fun.c 
fun.c: In function ‘main’:
fun.c:14: warning: passing argument 1 of ‘func’ discards qualifiers from pointer target type
fun.c:3: note: expected ‘char *’ but argument is of type ‘const char *’
[xxx@localhost strcpy]$ 

结果报错了,char *参数不能接受const char *参数。如果你把func的参数改成const char *就可以编译成功。const char *实质上使变量的权限降低了,变得更为安全;char *权限高一点,就变得不是安全,因为别人可以随意修改嘛。则变量只能沿着降低权限的方向上走,也就是朝着更安全的方向走,不能朝着更危险的方向上走。C++的拷贝构造函数的参数用const也是这个道理。



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

盼盼编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值