c - 仅 memcpy 不同的数据

标签 c

我有两个非常大的数组,我只想 memcpy 不同的数据。问题是,如果第二个数组中有零,它也会复制零并覆盖原始数据。问题是,零也是一个有效的数据项。我可以使用什么算法来仅 memcpy 不同的数据?

我尝试过的:

void *my_memcpy(void *dest, const void *src, size_t n)
{
    char *dp = (char*) dest;
    const char *sp = (char*) src;
    while (n--)
    {
        if (*sp != 0)
            *dp = *sp;
        dp++;
        sp++;
    }
    return dest;
}

int main()
{
    int test[4] = {1, 2, 3, 4};
    int test2[4] = {0, 0, 0, 5};
    my_memcpy(test, test2, 4);
    for (int i = 0; i < 4; ++i)
        cout << test[i];
}

最佳答案

有几个问题需要解决。

第一个问题是 my_memcpy 一次仅检查和复制一个 char,但您规定的要求只是复制非零 int值。要理解为什么这是一个问题,请考虑以下两个数组。

int test [4] = { 1, 2, 3, 4 };
int modified[4] = { 512, 0, 0, 0 };

在 32 位小端系统上,这些数组的内存如下所示

test      1 0 0 0   2 0 0 0   3 0 0 0   4 0 0 0
modified  0 2 0 0   0 0 0 0   0 0 0 0   0 0 0 0

调用 my_memcpy( test, modded, sizeof(test) ) 后,数组的内存将如下所示

test      1 2 0 0   2 0 0 0   3 0 0 0   4 0 0 0  

请注意,my_memcpy 会将 2 复制到数组的第二个位置,因为 2 是唯一的非零 修改后的数组中的 char 值。但这使得输出数组为

int test[4] = { 513, 2, 3, 4 };

这不是你想要的。

<小时/>

第二个问题出现在 main() 函数中。您将值 4 作为数组的大小传递。虽然 4 是数组中 int 值的数量,但它并不是数组的大小。该数组由 16 个 char 值组成(在 32 位系统上)。因此,您必须决定传递给 my_memcpy 的大小是数组大小(以字节为单位),还是数组中的整数数量.

<小时/>

我建议的解决方案是重写 my_memcpy 以使用 int 指针。

int *my_int_cpy( int *dest, const int *src, size_t count )
{
    while (count--)
    {
        if (*src != 0)
            *dest = *src;
        dest++;
        src++;
    }
    return dest;
}

int main()
{
    int test[] = {1, 2, 3, 4};
    int test2[] = {512, 0, 0, 5};
    int count = sizeof(test)/sizeof(test[0]);

    my_int_cpy( test, test2, count );
    for (int i = 0; i < count; ++i)
        printf( "%d\n", test[i] );
}

关于c - 仅 memcpy 不同的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25979157/

相关文章:

c - 如何使用自定义 libopenssl 构建 openldap

c - Apache C 模块创建,连接 SQLite 的问题

java - C 和 OOP 需要一点澄清

c - 错误: too few arguments to function 'strcmp'

c - 我不明白指针

c - memset() 中的错误 3D 数组

c - 有序链表的链表

c - C中读取多行多个数字(不指定数字的数量)

python - 我可以阻止 C++ dll 在 Python Ctypes 中加载吗?

c - srand(time(NULL)) 改变种子值的速度不够快