Simulate the implementation of the memmove function

analyze

memmove is a memory move function. Now we need to copy 1, 2, 3, and 4 in the array to the positions of 3, 4, 5, and 6.
write picture description here
If reverse copy is not considered, it will become
write picture description here
the original position of 3 and 4. Modify it to 1, 2, so it cannot be achieved.
You will find that the position of target 3 above is greater than the position of source 1, you need to copy from back to front in reverse, that is, there will be no conflict, and correct copy can be achieved
write picture description here

dest refers to the destination and src refers to the source.
code show as below

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
void * my_memmove(void * dest,const void * src,size_t count)
{
    void * ret = dest;
    assert(dest!=NULL);
    assert(src!=NULL);
    if(dest<src)
    {
        //前--后
        while(count--)
        {
            *(char*)dest = *(char*)src;
            dest = (char*)dest+1;
            src = (char*)src+1;

        }
    }
    else
    {    //从后向前
        while(count--)
        {
            *((char*)dest+count) = *((char*)src+count);
        }
    }
        return ret;
}

test code

int main()
{
    int arr1[]={1,2,3,4,5,6,7,8,9};
    int i = 0;
    for(i=0;i<9;i++)
    {
        printf("%d ",arr1[i]);
    }
    printf("\n");
    my_memmove(arr1+2,arr1,16);
    for(i=0;i<9;i++)
    {
        printf("%d ",arr1[i]);
    }
    system("pause");
    return 0;

}

achieve results
write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325763630&siteId=291194637