Note the relationship between the source memory address and the target address when copying the address, that is, whether the source memory address and the target address are crossed.
1. If there is no crossover, you can directly copy the data in a loop.
2. If there is crossover, there are also two types of crossover.
First:
In this case, Src> = DST & SRC <= DST + count-1
Second:
In this case, DST> SRC & DST <SRC + count-1.
The following uses an array: int arr [] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9:Memcpy (A, A + 4, sizeof (INT) * 6 );
First case:
Case 2:
The results in the figure show that the first crossover is the same as that without crossover, And you can directly copy them cyclically. However, if there is a crossover, it is necessary to copy the last byte of the source address from the front to the back.
BelowProgram, Just for reference
# Include <stdio. h> void * memcpy (void * DST, const void * SRC, size_t count) {char * p_dst = (char *) (DST); char * p_src = (char *) (SRC); unsigned int I; If (DST> SRC & (char *) DST <= (char *) SRC + count-1 )) // If p_dst = p_src, copy it directly. {// If p_dst = p_src + count-1, there is an overlap, while (count) {* (p_dst + count-1) = * (p_src + count-1); count -- ;}} else {for (I = 0; I <count; I ++) * (p_dst + I) = * (p_src + I);} return DST;} void main () {int arr [] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; memcpy (ARR + 4, arr, sizeof (INT) * 6); For (INT I = 0; I <10; I ++) printf ("% d \ t", arr [I]); printf ("\ n ");}
The preceding example is an example of the second test case. If it is incorrect, I hope to give a comment.