1.strcpy函數
函數原型:char *strcpy(char *dst,char const *src) 必須保證dst字符的空間足以保存src字符,否則多余的字符仍然被復制,覆蓋原先存儲在數組后面的內存空間的數值,strcpy無法判斷這個問題因為他無法判斷字符數組的長度。
1 #include <stdio.h> 2 #include<string.h> 3 int main() 4 { 5 6 char message[5]; 7 int a=10; 8 strcpy(message,"Adiffent"); 9 printf("%s %d",message,a); 10 return 0; 11 }
輸出結果是Adiffent 10;因此使用這個函數前要確保目標參數足以容納源字符串
2.strncpy函數:長度受限字符串函數
函數原型:char *strncpy(char *dst,char const *src,size_t len ) 要確保函數復制后的字符串以NUL字節結尾,即1<len<sizeof(*dst)
1 #include <stdio.h> 2 #include<string.h> 3 int main() 4 { 5 6 char message[5]; 7 int a=10; 8 strncpy(message,"Adiffent",2);//長度參數的值應該限制在(1,5) 9 printf("%s %d",message,a); //不包含1和5 10 return 0; 11 }
