如何复制内存 [英] How to copy memory

查看:122
本文介绍了如何复制内存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有

unsigned char *varA, *varB, *varC;
varA=malloc(64);
varB=malloc(32);
varC=malloc(32);

如何将第一个 32字节的varA放入varB,然后将最后一个 32字节的varA放入varC?

How can i put the first 32 byte of varA into varB and the last 32 byte of varA into varC?

推荐答案

memcpy(varB, varA, 32);
memcpy(varC, varA + 32, 32);

就这么简单,因为基础数据类型是unsigned char,它的大小与字节相同.如果varAvarBvarC是整数,则需要将memcpy(即32)的size参数乘以sizeof(int),以计算要复制的正确字节数.如果我在做书呆子,我可以在上面的示例中将sizeof(unsigned char)乘以32,但这不是必需的,因为sizeof(unsigned char) == 1.

It's this simple because the underlying data type is unsigned char, which is the same size as a byte. If varA, varB, and varC were integers, you would need to multiply the size parameter to memcpy (i.e. 32) by sizeof(int) to compute the right number of bytes to copy. If I were being pedantic, i could have multiplied 32 by sizeof(unsigned char) in the example above, but it is not necessary because sizeof(unsigned char) == 1.

请注意,我不需要将varA + 32中的32乘以任何值,因为当向指针添加常量偏移量时,编译器会为我执行此操作.

Note that I don't need to multiply the 32 in varA + 32 by anything because the compiler does that for me when adding constant offsets to pointers.

另一件事:如果想提高速度,只需要单独处理varA的每一半就足够了,而不是分配两个新的缓冲区并复制到其中.

One more thing: if you want to be fast, it might be sufficient to just work on each half of varA separately, rather than allocate two new buffers and copy into them.

这篇关于如何复制内存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆