C language simulation implements memcpy() of standard library function

memcpy()

1. If we need to initialize an array and set all the contents of the array to 0, can we use strcpy()

int main()
{
    char arr1[10] = { 0 };
    char arr2[10] = " abcdefg ";
    strcpy(arr2, arr1);
    system("pause");
    return 0;
}

We see that only one element of arr2[0] is assigned 0, while the rest of the elements remain unchanged. So we need a new function to complete the "memory copy "memcpy()"

memcpy()

函数的功能是从源src所指的内存地址的起始位置开始拷贝n个字节到目标dest所指的内存地址的起始位置中。

void * my_memcpy(void *dest, const void* src, int count)
{
    void * ret = dest;
    while (count--)
    {
        *(char *)dest = *(char *)src;
        dest = (char *)dest + 1;
        src = (char *)src + 1;
    }
    return ret;

}
int main()
{
    char arr1[10] = { 0 };
    char arr2[20] = "abcdef";

    printf("%s", my_memcpy(arr2, arr1, 6));

    system("pause");
}

write picture description here

Guess you like

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