複製字串。 這些函式已有更安全的版本可用,請參閱 strcpy_s、wcscpy_s、_mbscpy_s。
重要
在 Windows 執行階段中執行的應用程式中無法使用 _mbscpy。 如需詳細資訊,請參閱 CRT functions not supported in Universal Windows Platform apps (通用 Windows 平台應用程式中不支援的 CRT 函式)。
語法
char *strcpy(
char *strDestination,
const char *strSource
);
wchar_t *wcscpy(
wchar_t *strDestination,
const wchar_t *strSource
);
unsigned char *_mbscpy(
unsigned char *strDestination,
const unsigned char *strSource
);
template <size_t size>
char *strcpy(
char (&strDestination)[size],
const char *strSource
); // C++ only
template <size_t size>
wchar_t *wcscpy(
wchar_t (&strDestination)[size],
const wchar_t *strSource
); // C++ only
template <size_t size>
unsigned char *_mbscpy(
unsigned char (&strDestination)[size],
const unsigned char *strSource
); // C++ only
參數
strDestination
目的字串。
strSource
以 Null 結束的來源字串。
傳回值
所有這些函式都會傳回目的字串。 未保留表示錯誤的傳回值。
備註
strcpy 函式會將 strSource (包含結束的 null 字元) 複製到 strDestination 所指定的位置。 如果來源和目的字串重疊,則 strcpy 的行為未定義。
重要
因為 strcpy 在複製 strSource 之前不會檢查 strDestination 中是否有足夠的空間,所以這是緩衝區滿溢的潛在原因。 因此,建議您改用 strcpy_s 。
wcscpy 和 _mbscpy 分別是 strcpy 的寬字元版本和多位元組字元版本。 的自變數和傳回值 wcscpy 是寬字元字串。 的自變數和傳回值 _mbscpy 是多位元組位元元字串。 除此之外,這三個函式的行為相同。
在 C++ 中,這些函式具有樣板多載,可以叫用這些函式的更新且安全的對應版本。 如需詳細資訊,請參閱安全範本多載。
根據預設,此函式的全域狀態會限定於應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。
一般文字常式對應
TCHAR.H 常式 |
_UNICODE 和 _MBCS 未定義 |
_MBCS 已定義 |
_UNICODE 已定義 |
|---|---|---|---|
_tcscpy |
strcpy |
_mbscpy |
wcscpy |
需求
| 常式 | 必要的標頭 |
|---|---|
strcpy |
<string.h> |
wcscpy |
<string.h> 或 <wchar.h> |
_mbscpy |
<mbstring.h> |
如需相容性詳細資訊,請參閱相容性。
範例
// crt_strcpy.c
// compile with: /W3
// This program uses strcpy
// and strcat to build a phrase.
#include <string.h>
#include <stdio.h>
int main( void )
{
char string[80];
// If you change the previous line to
// char string[20];
// strcpy and strcat will happily overrun the string
// buffer. See the examples for strncpy and strncat
// for safer string handling.
strcpy( string, "Hello world from " ); // C4996
// Note: strcpy is deprecated; use strcpy_s instead
strcat( string, "strcpy " ); // C4996
// Note: strcat is deprecated; use strcat_s instead
strcat( string, "and " ); // C4996
strcat( string, "strcat!" ); // C4996
printf( "String = %s\n", string );
}
String = Hello world from strcpy and strcat!
另請參閱
字串操作
strcat、 、 wcscat_mbscat
strcmp、 、 wcscmp_mbscmp
strncat、、_strncat_lwcsncat、_wcsncat_l、、_mbsncat、_mbsncat_l
strncmp、 、 wcsncmp、 _mbsncmp_mbsncmp_l
strncpy、、_strncpy_lwcsncpy、_wcsncpy_l、、_mbsncpy、_mbsncpy_l
_strnicmp、、_wcsnicmp_mbsnicmp、_strnicmp_l、、_wcsnicmp_l、_mbsnicmp_l
strrchr、 、 wcsrchr、 _mbsrchr_mbsrchr_l
strspn、 、 wcsspn、 _mbsspn_mbsspn_l