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也是这个道理。