
- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - memcpy() 函式
C 庫的 memcpy() 函式也稱為複製記憶體塊函式/記憶體到記憶體複製。它用於指定字元範圍,該範圍不能超過源記憶體的大小。
語法
以下是 C 庫 memcpy() 函式的語法:
void *memcpy(void *dest_str, const void * src_str, size_t n)
引數
此函式接受以下引數:
dest_str - 此引數定義指向目標陣列的指標,目標陣列中將複製內容。它被型別轉換為 void* 型別的指標。
src_str - 此引數用於定義要複製的資料來源。然後將其型別轉換為 void* 型別的指標。
n - 此引數指的是要複製的位元組數。
返回值
此函式返回指向目標,即 dest_str 的指標。
示例 1
C 庫函式 memcpy() 使用三個引數:目標字串 (dest)、源字串 (src) 和 strlen() 函式,其中它計算源字串的長度和要複製的位元組數。
#include <stdio.h> #include <string.h> int main () { const char src[50] = "Tutorialspoint"; char dest[50]; strcpy(dest,"Heloooo!!"); printf("Before memcpy dest = %s\n", dest); memcpy(dest, src, strlen(src) + 1); printf("After memcpy dest = %s\n", dest); return(0); }
輸出
上述程式碼產生以下結果:
Before memcpy dest = Heloooo!! After memcpy dest = Tutorialspoint
示例 2
下面的程式使用兩個函式:puts() 和 memcpy() 將內容從一個記憶體地址/位置複製到另一個記憶體地址/位置。
#include <stdio.h> #include <string.h> int main() { char first_str[] = "Tutorials"; char sec_str[] = "Point"; puts("first_str before memcpy:"); puts(first_str); // Copy the content of first_str to sec_str memcpy(first_str, sec_str, sizeof(sec_str)); puts("\nfirst_str after memcpy:"); puts(first_str); return 0; }
輸出
執行上述程式碼後,我們將得到以下結果:
first_str before memcpy: Tutorials first_str after memcpy: Point
示例
以下是演示 memcpy() 函式程式碼片段的 C 程式,用於表示在使用某些操作或過程之前和之後的文字。
#include <stdio.h> #include <string.h> #define MAX_CHAR 100 int main() { char first_str[MAX_CHAR] = "Hello World!"; char second_str[MAX_CHAR] = "Welcome to Tutorialspoint"; printf("The Actual Statements:-\n"); printf("first_str: %s\n", first_str); printf("second_str: %s\n", second_str); //copying all bytes of second_str to first_str memcpy(first_str, second_str, strlen(second_str)); printf("After executing the function memcpy()\n"); printf("first_str: %s\n", first_str); printf("second_str: %s\n", second_str); return 0; }
輸出
執行程式碼後,我們將得到以下結果:
The Actual Statements:- first_str: Hello World! second_str: Welcome to Tutorialspoint After executing the function memcpy() first_str: Welcome to Tutorialspoint second_str: Welcome to Tutorialspoint
廣告