strcpy 和strcnpy函數——字符串復制函數。
1.strcpy函數
函數原型:char *strcpy(char *dst,char const *src) 必須保證dst字符的空間足以保存src字符,否則多余的字符仍然被復制,覆蓋原先存儲在數組后面的內存空間的數值,strcpy無法判斷這個問題因為他無法判斷字符數組的長度。
1
2
3
4
5
6
7
8
9
10
11
|
#include <stdio.h> #include<string.h> int main() { char message[5]; int a=10; strcpy (message, "Adiffent" ); printf ( "%s %d" ,message,a); return 0; } |
輸出結果是Adiffent 10;因此使用這個函數前要確保目標參數足以容納源字符串
2.strncpy函數:長度受限字符串函數
函數原型:char *strncpy(char *dst,char const *src,size_t len ) 要確保函數復制后的字符串以NUL字節結尾,即1<len<sizeof(*dst)
1
2
3
4
5
6
7
8
9
10
|
#include <stdio.h> #include<string.h> int main() { char message[5]; int a=10; strncpy (message, "Adiffent" ,2); //長度參數的值應該限制在(1,5) printf ( "%s %d" ,message,a); //不包含1和5 return 0; } |
總結
以上所述是小編給大家介紹的c語言中的 strcpy和strncpy字符串函數使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/chunmu/p/9844023.html