strcpy 和strcnpy函數(shù)——字符串復(fù)制函數(shù)。
1.strcpy函數(shù)
函數(shù)原型:char *strcpy(char *dst,char const *src) 必須保證dst字符的空間足以保存src字符,否則多余的字符仍然被復(fù)制,覆蓋原先存儲在數(shù)組后面的內(nèi)存空間的數(shù)值,strcpy無法判斷這個(gè)問題因?yàn)樗麩o法判斷字符數(shù)組的長度。
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; } |
輸出結(jié)果是Adiffent 10;因此使用這個(gè)函數(shù)前要確保目標(biāo)參數(shù)足以容納源字符串
2.strncpy函數(shù):長度受限字符串函數(shù)
函數(shù)原型:char *strncpy(char *dst,char const *src,size_t len ) 要確保函數(shù)復(fù)制后的字符串以NUL字節(jié)結(jié)尾,即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); //長度參數(shù)的值應(yīng)該限制在(1,5) printf ( "%s %d" ,message,a); //不包含1和5 return 0; } |
總結(jié)
以上所述是小編給大家介紹的c語言中的 strcpy和strncpy字符串函數(shù)使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時(shí)回復(fù)大家的。在此也非常感謝大家對服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://www.cnblogs.com/chunmu/p/9844023.html