void *memcpy(void *dest, const void *src, size_t n);
以 src 所指位址為起點,連續複製 n 個位元組的資料,寫入以 dest 所指位址為起點的記憶體空間中。
#include <string.h>
函數回傳一個指向 dest 的指標。
一、記憶體不可重疊。src 與 dest 所指的記憶體區域不能重疊,否則行為未定義;若確定會重疊,請改用 memmove()。函數執行後回傳指向 dest 的指標。
二、與 strcpy 的差別。memcpy 不會碰到 '\0' 就停手,它一定會拷完 n 個位元組。因此它能複製任何型別的物件(結構、整數陣列、二維資料等),長度由你自己指定;strcpy 只能處理字串,遇到結束符就收工。
char a[100], b[50]; memcpy(b, a, sizeof(b)); /* 若寫成 sizeof(a),會造成 b 的位址溢位 */ strcpy(a, b); /* strcpy 僅能複製字串 */
三、覆蓋而非追加。若目標陣列 dest 原本已有資料,memcpy 會直接覆寫(最多覆寫 n 個位元組)。若想追加,每次呼叫後要手動把目標位址往前推到要寫入的位置。
另外別忘了:src 與 dest 都不一定是陣列,任何可讀寫的記憶體空間都可以。
將 s 中的字串複製到字元陣列 d 中。
/* memcpy.c */
#include <stdio.h>
#include <string.h>
int main()
{
char *s = "Golden Global View";
char d[20];
memcpy(d, s, strlen(s));
d[strlen(s)] = '\0'; /* 從 d[0] 開始複製,長度為 strlen(s),故 d[strlen(s)] 置結束符 */
printf("%s", d);
getchar();
return 0;
}
/* 輸出結果:Golden Global View */
將 s 中第 14 個字元(V)起連續 4 個字元複製到 d 中(索引從 0 開始)。
#include <string.h>
int main()
{
char *s = "Golden Global View";
char d[20];
memcpy(d, s + 14, 4); /* 複製 "View" */
/* memcpy(d, s + 14 * sizeof(char), 4 * sizeof(char)); 亦可 */
d[4] = '\0';
printf("%s", d);
getchar();
return 0;
}
/* 輸出結果:View */
#include <stdio.h>
#include <string.h>
int main(void)
{
char src[] = "******************************";
char dest[] = "abcdefghijlkmnopqrstuvwxyz0123as6";
printf("destination before memcpy: %s\n", dest);
memcpy(dest, src, strlen(src));
printf("destination after memcpy: %s\n", dest);
return 0;
}
/* 輸出結果:
destination before memcpy: abcdefghijlkmnopqrstuvwxyz0123as6
destination after memcpy: ******************************as6
*/
可以看到前 30 個位元組被星號整段覆寫,後面的 "as6" 則原封不動,這正是 memcpy「按長度硬拷」的特性。