C language: memcpy() usage details

1. Introduction to memcpy()

1.1 Function prototype

void *memcpy(void *destin, void *source, unsigned n);

1.2 Parameters

  • destin -points to the target array used to store the copied content, and the type is cast to a void* pointer.
  • source -points to the data source to be copied, the type is cast to void* pointer.
  • n -the number of bytes to be copied.

1.3 Function

Copy n bytes from the starting position of the memory address pointed to by the source source to the starting position of the memory address pointed to by the target destin.

1.4 Header files

#include<string.h>

1.5 Return value

This function returns a pointer to the target storage area destin.

2. Memcpy() usage

If the target array destin itself has data, after executing memcpy(), the original data will be overwritten (at most n). If you want to append data, after each execution of memcpy, you need to increase the target array address to the address where you want to append data.
The specific code is as follows:

#include <stdio.h>
#include <string.h>

int main(void)
{
    
    
	char data[7]="memcpy";
	printf("%s\n",data);
	
	char cdata[20]={
    
    0};	
	memcpy(cdata,data,6);
 	printf("%s\n",cdata);
	memcpy(cdata,"123456",6); 
	printf("%s\n",cdata);
	memcpy(&cdata[6],"78910",6); //追加数据
 	printf("%s\n",cdata);
 	
	return 0;
}

The running result is as follows:

memcpy
memcpy
123456
12345678910

Guess you like

Origin blog.csdn.net/MQ0522/article/details/110949280