memcpy() 函數
memcpy() 是一個庫函數,它在“string.h”頭文件中聲明——用於將一塊內存從一個位置複製到另一個位置(也可以認為是將一個字符串複製到另一個位置) .
memcpy() 的語法:
memcpy(void*str1, const void* str2, size_t n);
它複製n
字節str2
至str1
。
示例 1)將一個字符串複製到另一個(一個字符串的所有字節都複製到另一個)
#include <stdio.h>
#include <string.h>
#define MAX_CHAR 50
int main(void) {
char str1[MAX_CHAR] = "Hello World!";
char str2[MAX_CHAR] = "Nothing is impossible";
printf("Before copying...\n");
printf("str1:%s\n",str1);
printf("str2:%s\n",str2);
//copying all bytes of str2 to str1
memcpy(str1, str2, strlen(str2));
printf("After copying...\n");
printf("str1:%s\n", str1);
printf("str2:%s\n", str2);
return 0;
}
輸出
Before copying... str1:Hello World! str2:Nothing is impossible After copying... str1:Nothing is impossible str2:Nothing is impossible
示例 2) 將一些字節從一個字節數組複製到另一個數組
#include <stdio.h>
#include <string.h>
#define MAXLEN 11
//function to print array
void printArray(unsigned char str[], int length){
int i;
for(i=0; i<length;i++)
printf("%02X ", str[i]);
printf("\n");
}
int main(void) {
unsigned char arr1[MAXLEN] = {0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0x95};
unsigned char arr2[MAXLEN] = {0};
printf("Before copying...\n");
printf("arr1:"); printArray(arr1, strlen(arr1));
printf("arr2:"); printArray(arr2, strlen(arr2));
//copying 5 bytes of arr1 to arr2
memcpy(arr2, arr1, 5);
printf("After copying...\n");
printf("arr1:"); printArray(arr1, strlen(arr1));
printf("arr2:"); printArray(arr2, strlen(arr2));
return 0;
}
相關用法
- C語言 memset()用法及代碼示例
- C語言 moveto()用法及代碼示例
- C語言 modf()用法及代碼示例
- C語言 moverel()用法及代碼示例
- C語言 fread()用法及代碼示例
- C語言 feof()用法及代碼示例
- C語言 imagesize()用法及代碼示例
- C語言 getarcoords()用法及代碼示例
- C語言 strcspn()用法及代碼示例
- C語言 setlinestyle()用法及代碼示例
- C語言 showbits()用法及代碼示例
- C語言 sprintf()用法及代碼示例
- C語言 outtextxy()用法及代碼示例
- C語言 isgraph()用法及代碼示例
- C語言 grapherrormsg()用法及代碼示例
- C語言 putchar()用法及代碼示例
- C語言 tmpnam()用法及代碼示例
- C語言 putpixel()用法及代碼示例
- C語言 fillellipse()用法及代碼示例
- C語言 outtext()用法及代碼示例
注:本文由純淨天空篩選整理自 memcpy() function in C with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。