我为 memcpy 找到了以下实现(面试问题,其中迭代计数 ~ size/4):
void memcpy(void* dest, void* src, int size)
{
uint8_t *pdest = (uint8_t*) dest;
uint8_t *psrc = (uint8_t*) src;
int loops = (size / sizeof(uint32_t));
for(int index = 0; index < loops; ++index)
{
*((uint32_t*)pdest) = *((uint32_t*)psrc);
pdest += sizeof(uint32_t);
psrc += sizeof(uint32_t);
}
loops = (size % sizeof(uint32_t));
for (int index = 0; index < loops; ++index)
{
*pdest = *psrc;
++pdest;
++psrc;
}
}
而且我不确定我是否理解它.....:
1)为什么要定义uint8_t *pdest,uint8_t *psrc
并在此之后进行强制转换uint32_t
-
*((uint32_t*)pdest) = *((uint32_t*)psrc);
我认为从一开始就pdest
应该psrc
定义为 uint32_t ...我错过了什么?2)在我看来,这个实现存在问题:如果src = 0x100
和dst = 0x104
src(最初)看起来像这样:
-------------------------
| 6 | 8 | 7 | 1 |
-------------------------
0x100 0x104 0x108 0x1C0
执行后会是这样
-------------------------
| 6 | 6 | 6 | 6 |.....
-------------------------
0x100 0x104 0x108 0x1C0
尽管看起来下面的内存布局应该是结果
-------------------------
| 6 | 6 | 8 | 7 |....
-------------------------
0x100 0x104 0x108 0x1C0