首页 > 编程知识 正文

c语言实现memcpy,c++实现memcpy函数

时间:2023-05-05 21:19:22 阅读:256222 作者:943

c语言中memcpy函数

memcpy()函数 (memcpy() function)

memcpy() is a library function, which is declared in the “string.h” header file - it is used to copy a block of memory from one location to another (it can also be considered as to copy a string to another).

memcpy()是一个库函数,在“ string.h”头文件中声明-它用于将一个内存块从一个位置复制到另一个位置(也可以视为将字符串复制到另一个位置)。

Syntax of memcpy():

memcpy()的语法:

memcpy(void*str1, const void* str2, size_t n);

It copies n bytes of str2 to str1.

它将str2的 n个字节复制到str1中 。

Example 1) Copying a string to another (all bytes of a string to another)

示例1)将一个字符串复制到另一个(字符串的所有字节到另一个)

#include <stdio.h>#include <string.h>#define MAX_CHAR 50int main(void) {char str1[MAX_CHAR] = "Hello World!";char str2[MAX_CHAR] = "Nothing is impossible";printf("Before copying...n");printf("str1: %sn",str1);printf("str2: %sn",str2);//copying all bytes of str2 to str1memcpy(str1, str2, strlen(str2));printf("After copying...n");printf("str1: %sn", str1);printf("str2: %sn", str2);return 0;}

Output

输出量

Before copying...str1: Hello World!str2: Nothing is impossibleAfter copying...str1: Nothing is impossiblestr2: Nothing is impossible .minHeight{ min-height: 250px; } @media (min-width: 1025px){ .minHeight{ min-height: 90px; } } .minHeight{ min-height: 250px; } @media (min-width: 1025px){ .minHeight{ min-height: 90px; } }

Example 2) Copying some of the bytes from a byte array to another array

示例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 arr2memcpy(arr2, arr1, 5);printf("After copying...n");printf("arr1: "); printArray(arr1, strlen(arr1));printf("arr2: "); printArray(arr2, strlen(arr2));return 0;}

Output

输出量

Before copying...arr1: 10 20 30 40 50 60 70 80 90 95arr2:After copying...arr1: 10 20 30 40 50 60 70 80 90 95arr2: 10 20 30 40 50

翻译自: https://www.includehelp.com/c-programs/memcpy-function-in-c-with-example.aspx

c语言中memcpy函数

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。