个人主页: 会编程的果子君
个人格言:“成为自己未来的主人~”
目录
memcpy使用和模拟实现
memmove的使用和模拟实现
memset函数的使用
memcmp函数的使用
void *memcpy (void*destination,const void * source,size_t num)
#include
#include
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
memcpy(arr1, arr2, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d", arr2[i]);
}
return 0;
}
对于重叠的内存,交给memmove来处理
memcpy函数的模拟实现
#include
#include
#include
void * my_memcpy(void* dest,void * src,size_t num)
{
void* ret = dest;
assert(dest, src);
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
int arr2[10] = { 0 };
my_memcpy(arr1, arr2, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d", arr2[i]);
}
return 0;
}
void *memmove(void* destination,const void*source,size_t num)
和memcpy的差别就是memmove函数处理的源内存块和目标内存块 是可以重叠的
如果源空间和目标空间出现重叠,就得使用memmovr函数处理
#include
#include
int main()
{
int arr1[] = { 1,2,3,4,5,6,7,8,9,10 };
memmove(arr1 + 2, arr1, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d", arr1[i]);
}
return 0;
}
#include
#include
#include
void* my_memmove(void* dest, const void* src, size_t num)
{
assert(dest && src);
void* ret = dest;
if (dest <= src || (char*)dest>=((char*)src+num))
{
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
dest = (char*)dest+ num - 1;
src = (char*)src+ num - 1;
while (num--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest - 1;
src = (char*)src - 1;
}
}
return ret;
}
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
my_memmove(arr + 2, arr, 20);
int i = 0;
for (i = 0; i < 10; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
void*memset(void*ptr,int value,size_t num)
memset是用来设置内存的,将内存中的值以字节为单位设置成想要的内容
#include
#include
int main()
{
char arr[] = "hello world";
memset(arr, 'x', 6);
print(arr);
return 0;
}
int memcmp(const void* part1,const void*part2,size_t num)
#include
#include
int main()
{
char butter1[] = { 1,2,3,4,5,6,1 };
char butter2[] = { 1,2,3,4,5,6,0 };
int n;
n = memcmp(butter1, butter2, 5 * sizeof(butter1[0]));
printf("%d",n);
return 0;
}