为什么 memmove() 函数以这种方式工作?

Why memmove() function works this way?

我在 Stack Overflow 上遇到了与 memmove()memcpy() 相关的各种问题。

有这个post暗示如果源地址(要复制的数据)大于目标地址(要复制到的数据),则执行正向复制,否则执行反向正在复制。

为什么会这样?我在这两种情况下都尝试了正向复制,并且工作得很好,没有任何错误。

能详细说说吗?我不明白原因。

编辑:这就是我想说的:

#include <memory.h> 
#include <string.h>
#include <stdio.h>

void *memmoveCustom(void *dest, const void *src, size_t n)
{
    unsigned char *pd = (unsigned char *)dest;
    const unsigned char *ps = (unsigned char *)src;
    if ( ps < pd )
        for (pd += n, ps += n; n--;)
            *--pd = *--ps;
    else
        while(n--)
            *pd++ = *ps++;
    return dest;
}

int main( void )
{
    printf( "The string: %s\n", str1 );

    memmoveCustom( str1 + 1, str1, 9 );
    printf( "Implemented memmove output: %s\n", str1 );

    getchar();
}

以上程序是实现自定义 memmove() 函数的示例代码。 在函数内部,您可以看到当源地址大于目标地址时,它执行正向复制,否则它向现有地址添加 n-location 并执行从后向复制。 就是这样。

if the source address(data to be copied from) is greater than destination address(data to be copied to), it will perform forward copying otherwise it will perform backward copying.

这仅在 fromto 范围 重叠 时才重要。对于非重叠范围,复制方向无关紧要。

重叠范围很重要,因为如果您从头开始复制,您将在开始复制之前破坏源数据。