为什么 memcpy() 无法复制同一数组中的数组元素但具有偏移量

Why memcpy() fails copying elements of an array in the same array but with an offset

我正在尝试将数组的内容复制到自身内部,但有一个偏移量(或从一个偏移量开始)。例如:

int main(void) {
    char a[4] = { 'a', 'b' , 'c', 'd' }, b[4], c[4];

    memcpy(b, a, 4);
    memcpy(c, b, 4);

    memcpy(b, b + 1, 3);
    memcpy(c + 1, c, 3);

    for(unsigned i = 0; i < 4; i++)
        printf("%c", b[i]);
    printf("\n");

    for(unsigned i = 0; i < 4; i++)
        printf("%c", c[i]);

    return 0;
}

给出以下输出:

bcdd
aaaa

我在期待

bcdd
aabc

第一个 memcpy 有效,但第二个无效,我觉得它不一致,所以我做错了什么。

我不明白我做错了什么。为什么会失败。另外,如果我尝试做同样的事情,但对于结构数组,例如,这仍然会发生吗?

2018 C 标准在第 7.24.2.1 条中指定 memcpy。第 2 段说:

… If copying takes place between objects that overlap, the behavior is undefined.

要在数组内移动数据,请使用 memmove。它的规范,在 7.24.2.2 2 中说:

Copying takes place as if the n characters from the object pointed to by s2 are first copied into a temporary array of n characters that does not overlap the objects pointed to by s1 and s2, and then the n characters from the temporary array are copied into the object pointed to by s1.

s1 是目标,s2 是源,n 是要复制的字节数。)