memcpy函数 |
---|
void *memcpy( void *dest, const void *src, size_t count ); |
经查阅:
The memcpy function copies count bytes of src to dest. If the source and destination overlap, this function does not ensure that the original source bytes in the overlapping region are copied before being overwritten. Use memmove to handle overlapping regions.
memcpy函数将src的计数字节复制到dest。 如果源和目标重叠,则此函数不会确保在覆盖之前复制重叠区域中的原始源字节。 使用memmove处理重叠区域。
memmove函数 |
---|
void *memmove( void *dest, const void *src, size_t count ); |
memmove函数将字节的字节数从src复制到dest。 如果源区域和目标的某些区域重叠,则memmove可确保在覆盖之前复制重叠区域中的原始源字节。
因此,两个函数的模拟实现如下:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<assert.h>
void *MyMemcpy(void *str1, void *str2, int count)
{
assert(str1 != NULL&&str2!=NULL);
void *ret = str1;
while (count--)
{
*(char *)str1 = *(char *)str2;
((char *)str1)++;
((char *)str2)++;
}
return ret;
}
int main()
{
int i = 0;
int str1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int str2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
MyMemcpy(str1 + 2, str1, 16);
for (i = 0; i < 9; i++)
{
printf("%d ", str1[i]);
}
printf("\n");
system("pause");
return 0;
}
结果展示
void *MyMemmove(void *str1, void *str2, int count)
{
assert(str1 != NULL&&str2 != NULL);
if (str1 < str2)
{
while (count--)//从前往后赋值
{
*(char *)str1 = *(char *)str2;
((char *)str1)++;
((char *)str2)++;
}
}
else
{
while (count--)//从后往前赋值
{
*((char *)str1 + count) = *((char *)str2 + count);
}
}
}
int main()
{
int i = 0;
int str1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
MyMemmove(str1 + 2, str1, 16);
for (i = 0; i < 9; i++)
{
printf("%d ", str1[i]);
}
printf("\n");
system("pause");
return 0;
}
结构展示