Do not use the library function to write out void * memcpy (void * DST, const void * SRC, size_t count), where DST is the destination address and SRC is the source address.

Source: Internet
Author: User

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.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.