一、函数定义
void * memcpy ( void * destination, const void * source, size_t num );
将source指向的地址处的 num 个字节 拷贝到 destination 指向的地址处。注意,是字节。
实现:
void* memcpy(void* dest, const void* source, size_t count)
{
char *ret = (char *)dest;
char *dest_t = ret;//中间变量
char *source_t = (char *)source;//中间变量
while (count--)
{
*dest_t++ = *source_t++;
}
return ret;
}
二、实例
int main() {
int a[10] = { 0,1,2,3,4,5,6,7,8,9 };
memcpy(a + 3, a, 5);
for (int i = 0; i<10; i++){
printf("%d ", a[i]);
}
return 0;
}
输出:0 1 2 0 1 5 6 7 8 9
int main() {
int a[10] = { 0,1,2,3,4,5,6,7,8,9 };
memcpy(a + 3, a, 5*sizeof(int));
for (int i = 0; i<10; i++){
printf("%d ", a[i]);
}
return 0;
}
输出:0 1 2 0 1 2 0 1 8 9