一、函数介绍
memcpy(拷贝内存)
函数功能:拷贝内存
头文件:<memory.h> 或者 <string.h>
返回值:返回dest的首元素地址
void *memcpy(void *destin, void *source, unsigned n);
#include <stdio.h>
#include <string.h>
struct
{
char name[40];
int age;
} person, person_copy;
int main ()
{
char myname[] = "Pierre de Fermat";
memcpy ( person.name, myname, strlen(myname)+1 );
person.age = 46;
memcpy ( &person_copy, &person, sizeof(person) );
printf ("person_copy: %s, %d \n", person_copy.name, person_copy.age );
return 0;
}
memmove(覆盖拷贝)
函数功能:覆盖拷贝
头文件:<string.h>
返回值:返回dest的首元素地址
void *memmove(void *dest, const void *source, size_t count)
#include <stdio.h>
#include <string.h>
int main()
{
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int* ret = memmove(arr + 2, arr, 20);
int i = 10;
for (i = 0; i < 10; i++)
{
printf("%d ",arr[i]);
}
return 0;
}
memcmp
函数功能:比较内存区域buf1和buf2的前count个字节
注意:是逐字节进行比较!!!
头文件:<memory.h> 或者 <string.h>
返回值:
①当buf1<buf2时,返回值<0
②当buf1=buf2时,返回值=0
③当buf1>buf2时,返回值>0
int memcmp(const void *buf1, const void *buf2, unsigned int count);
#include<string.h>
#include<stdio.h>
int main()
{
char s1[] = "Hello";
char s2[] = "Hello";
int r;
r = memcmp(&s1, &s2, strlen(s1));
if (!r)
printf("s1 and s2 are identical\n");
else if (r < 0)
printf("s1 is less than s2\n");
else
printf("s1 is greater than s2\n");
return 0;
}
memset
函数功能:是一个初始化函数,作用是将某一块内存中的全部设置为指定的值
注意:是以字节为单位进行初始化的!!!
头文件:<memory.h> 或者 <string.h>
返回值:dest的首元素地址
void *memset( void *dest, int c, size_t count );
#include<string.h>
#include<stdio.h>
int main()
{
int arr[5] = { 1,2,3,4,5 };
memset(arr,0,20);
int i = 0;
for (i = 0; i < 5; i++)
{
printf("%d ",arr[i]);
}
return 0;
}
二、函数的模拟实现
memcpy
#include <stdio.h>
#include <assert.h>
void* my_memcpy(void* dest, const void* src, size_t count)
{
assert(dest && src);
void* ret = dest;
while (count--)
{
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
return ret;
}
int main()
{
int arr1[10] = {1,2,3,4,5,6,7,8,9,10};
int arr2[5] = { 0 };
my_memcpy(arr2,arr1,20);
return 0;
}
memmove
//可以实现重叠内存的拷贝
#include <stdio.h>
#include <assert.h>
void* my_memmove(void* dest, const void* src, size_t count)
{
assert(dest && src);
void* ret = dest;
if (dest < src)
{
//前->后
while (count--)
{
*(char*)dest = *(char*)(src);
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else
{
//后->前
while (count--)
{
*((char*)dest + count) = *((char*)src + count);
}
}
return ret;
}
int main()
{
int arr[10] = {1,2,3,4,5,6,7,8,9,10};
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
my_memmove(arr + 2,arr,20);
for (i = 0; i < sz; i++)
{
printf("%d ",arr[i]);
}
return 0;
}
注:本次学习就暂时结束啦,文章中有错误、不足之处欢迎大佬指正,让我们共同学习,共同进步,欲戴王冠,必承其重,加油!