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也是這個道理。
總結
- 上一篇: makefile入门
- 下一篇: makefile中使用变量