memcpy是内存复制函数,原型如下
void *memmove(void *dest, const void *src, size_t count)
从src地址复制count个字节到dest
模拟实现
void *memcpy(void *dest, const void *src, size_t count) {if (dest == NULL || src == NULL)return NULL;void *ans = dest;for (int i = 0; i < count; ++i) {*((char *) dest + i) = *((char *) src + i);}return ans;
}
无法处理重叠问题,如123456789自移动12345成为123412345,用memcpy会变成123412341,因为后移动的元素已经被先前移动的覆盖
于是有memove可以处理这种情况,原型
void * memmove ( void * destination, const void * source, size_t num )
从后往前复制可以避免这种情况
void *memmove(void *dest, const void *src, size_t count) {if (dest == NULL || src == NULL)return NULL;void *ans = dest;if (dest < src)for (int i = 0; i < count; ++i) {*((char *) dest + i) = *((char *) src + i);}elsewhile (--count) {*((char *) dest + count) = *((char *) src + count);}return ans;
}
测试
int main() {char cpy[] = "123456789";memcpy(cpy + 4, cpy, 5);std::cout << cpy << std::endl;char move[] = "123456789";memmove(move + 4, move, 5);std::cout << move;
}