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
广告
© . All rights reserved.