Reprint ------------ memcpy () function usage of C function, memcpy function usage
Reprinted on http://blog.csdn.net/tigerjibo/article/details/6841531
Function prototype
Void * memcpy (void * dest, const void * src, size_t n );
Function
Data of n consecutive bytes directed by src to the starting address is copied to the space with the starting address indicated by destin.
Header file
# Include <string. h>
Return Value
The function returns a pointer to dest.
Description
1. The source and destin memory regions cannot overlap. The function returns a pointer to destin.
2. Compared with strcpy, memcpy does not end when '\ 0' is encountered, but will definitely copy n Bytes.
Memcpy is used for memory copying. You can use it to copy any data type object and 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 of B may overflow.
Strcpy can only copy strings. It ends copying when '\ 0' is encountered. For example:
Char a [100], B [50];
Strcpy (a, B );
3. If the target array destin already has data, after memcpy () is executed, the original data will be overwritten (n at most ). If you want to append data, you need to add the target array address to the address where you want to append the data after executing memcpy.
// Note that both source and destin are not necessarily arrays, and any readable and writable space is acceptable.
Program example
Example1
Purpose: copy the string in s to the character array d.
// Memcpy. c
# Include <stdio. h>
# Include <string. h>
Intmain ()
{
Char * s = "Golden Global View ";
Chard [20];
Clrscr ();
Memcpy (d, s, strlen (s ));
D [strlen (s)] = '\ 0'; // because replication starts from d [0], the total length is strlen (s), d [strlen (s)] set to Terminator
Printf ("% s", d );
Getchar ();
Return0;
}
Output result: GoldenGlobal View
Example2
Purpose: copy the four consecutive characters starting with 14th characters in s to d. (Starting from 0)
# Include <string. h>
Intmain ()
{
Char * s = "Golden Global View ";
Chard [20];
Memcpy (d, s + 14th); // starts copying from characters (V) and continues copying 4 characters (View)
// Memcpy (d, s + 14 * sizeof (char), 4 * sizeof (char );
D [4] = '\ 0 ';
Printf ("% s", d );
Getchar ();
Return0;
}
Output result: View
Example3
Purpose: Copy and overwrite the original data.
# Include <stdio. h>
# Include <string. h>
Intmain (void)
{
Charsrc [] = "******************************";
Chardest [] = "abcdefghijlkmnopqrstuvwxyz0123as6 ";
Printf ("destinationbefore memcpy: % s \ n", dest );
Memcpy (dest, src, strlen (src ));
Printf ("destinationafter memcpy: % s \ n", dest );
Return0;
}
Output result:
Destinationbefore memcpy: abcdefghijlkmnopqrstuvwxyz0123as6
Destinationafter memcpy: ******************************* as6