strcpy和strncpy的區別以及模擬實現

2021-08-20 03:21:53 字數 2213 閱讀 1460

strcpy(字串拷貝)

原型:

標頭檔案:#include< string.h >

引數: 第乙個引數為:目標字串。第二個引數為源字串。

返回型別:char*。

作用: 把源字串(strsource)拷貝到目標字串(strdestination)上。

注意事項:1. 目標空間必須足夠大且可以被修改;2. 源字串中必須有『\0』;3. 源字串不可以被修改。

參考**(庫函式實現):

#include

#include

int main()

; //目標空間足夠大

strcpy(s, p);

printf("%s\n", s);

system("pause");

return

0;}

執行:

模擬實現strcpy

**:

#include

#include

#include

char * my_strcpy(char *dest,const

char *src)

return ret;

}int main()

; //目標空間必須足夠大

char*ret=my_strcpy(s, p);

printf("%s\n", ret);

system("pause");

return

0;}

執行:

strncpy(長度受限制的字串拷貝)

原型:

裡面的count是指:

即複製多少個。

標頭檔案:#include< string.h>

引數:第乙個引數為:目標字串。第二個引數為源字串。第三個引數為無符號的整形數。

返回型別:char*。

作用:把源字串(strsource)中的count個字元拷貝到目標字串(strdest)中。

注意事項:目標空間必須足夠大且可以被修改,源字串不可以被修改,如果源字串的長度小於count個,則拷貝完有效字串之後,在目標後面追加乙個\0。

參考**(庫函式實現):

#define _crt_secure_no_warnings 1

#include

#include

#include

int main()

執行(源字串的長度大於等於count):

執行(源字串的長度小於count):

模擬實現strncpy

**:

#define _crt_secure_no_warnings 1

#include

#include

#include

char* my_strncpy(char *dest, const

char *src, size_t count)

else

//count>源字串長度,拷貝完字串之後,

}return ret;

}int main()

執行(源字串的長度大於等於count):

執行(源字串的長度小於count):

strcpy和strncpy的區別

strcpy 原型 char strcpy char restrict s1,const char restrict s2 用法 include 功能 把s2所指由null結束的字串複製到s1所指的陣列中。說明 s1和s2所指記憶體區域不可以重疊且s1必須有足夠的空間來容納s2的字串。返回指向s1的...

strcpy和strncpy的區別

第一種情況 1 2 3 4 char p how are you char name 20 abcdefghijklmnopqrs strcpy name,p name改變為 how are you 正確!strncpy name,p,sizeof name name改變為 how are you ...

strncpy 和strcpy的區別

1.strcpy函式 顧名思義字串複製函式 原型 extern char strcpy char dest,char src 功能 把從src位址開始且含有null結束符的字串賦值到以dest開始的位址空間,返回dest 位址中儲存的為複製後的新值 要求 src和dest所指記憶體區域不可以重疊且d...