C/C++ strcpy 用法與範例

本篇 ShengYu 介紹 C/C++ strcpy 用法與範例,strcpy 是用來複製字串的函式,另外有個 strncpy 函式也是同樣功能,但安全性更高,在下列文章一併一起介紹。

C 語言要判斷 c-style 字串是否相等通常會使用 strcpy,要使用 strcpy 的話需要引入的標頭檔 <string.h>,如果要使用 C++ 的標頭檔則是引入 <cstring>
strcpy 函式原型為

1
char * strcpy(char * destination, const char * source);

strcpy 會將 source 複製到 destination 裡,包含 \0 結束字元,並且遇到 \0 結束字元就停止複製,
除了 strcpy 以外,像 strlen 這種函數在操作字串時, 也都會需要用字串最後的 \0 結束字元當做字串結束的判斷,
以下來看看 strcpy 怎麼複製字串,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// g++ cpp-strcpy.cpp -o a.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // strcpy

int main() {
char str[] = "Hello world";
char str2[64];
strcpy(str2, str);
printf("%s\n", str);

char str3[64];
strcpy(str3, "This is a string");
printf("%s\n", str3);
return 0;
}

結果如下,

1
2
Hello world
This is a string

常見考題

請問下列程式有什麼問題?

1
2
3
char* src = "0123456789";
char dst[10];
strcpy(dst, src);

問題在於 dst 分配了 10 大小的 char 字元陣列 char dst[10]; 總共有 10 個位置,而 src 字串實際佔 11 字元空間(包含結束字元),strcpy 時會造成 buffer overflow,意思就是 0123456789 這個字串 需要 11 個字元的位置才夠放,

在實務上通常會需要儘量少用 strcpy, 而改用 strncpy,strncpy 比 strcpy 多了第三個引數,第三個引數是傳入要複製幾個字元的數量,
所以我們這邊複製字串時最大長度不應超過 dst 的大小,

1
2
strncpy(dst, src, sizeof(dst)-1);
dst[sizeof(dst)-1] = '\0';

範例程式如下,

cpp-strncpy.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// g++ cpp-strncpy.cpp -o a.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // strncpy

int main() {
char* src = "0123456789";
char dst[10];

strncpy(dst, src, sizeof(dst)-1);
dst[sizeof(dst)-1] = '\0';

printf("%s\n", dst);
return 0;
}

輸出結果如下,

1
012345678

以上就是 C/C++ strcpy 的用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它參考
strcpy - C++ Reference
https://www.cplusplus.com/reference/cstring/strcpy/

其它相關文章推薦
如果你想學習 C++ 相關技術,可以參考看看下面的文章,
C/C++ 新手入門教學懶人包
C/C++ memcpy 用法與範例
C/C++ strcmp 用法與範例
C/C++ strcat 用法與範例
C/C++ strstr 用法與範例
C/C++ strtok 用法與範例