15, Linux memcpy function

 

Function prototype

 

void *memcpy(void*dest, const void *src, size_t n);

 

function

 

Data of N consecutive bytes from SRC to address is copied into a space where destination to address is the starting address.

 

header file

 

#include<string.h>

 

Return value

 

  The function returns a pointer to dest.

 

 

Explain

 

  1.sourceAnd Destin refers to the memory area can not be overlapped, the function returns a pointer to Destin.

 

  2.Compared with strcpy, memcpy does not end with’\0′, but it will copy n bytes.

  memcpyUsed for memory copy, you can use it to copy any data type of object, you can specify the length of the copied data;

Example:

  char a[100], b[50];

  memcpy(b, a,sizeof(b)); //Note that if sizeof (a) is used, the memory address overflow of B will occur.

  strcpyYou can only copy the string, and it ends with’\0′.

  char a[100], b[50];

  strcpy(a,b);

 

  3.If the destination array itself already has data, after executing memcpy (), it will overwrite the original data (up to n). If you want to append data, each time you perform memcpy, add the address of the target array to the address where you want to append data.

 

  //Note that source and Destin are not necessarily arrays. Any readable and written space is acceptable.

【Example]

 

//memcpy.c

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

int main()
{
   char*s="Golden Global View";
  chard[20];
  clrscr();
  memcpy(d,s,strlen(s));
  d[strlen(s)]='\0';//Because the copy starts from d[0], the total length is strlen (s), and d[strlen (s)] is terminated.
  printf("%s",d);
  getchar();
  return0;
}     

 

results of enforcement

GoldenGlobal View

 

Leave a Reply

Your email address will not be published. Required fields are marked *