43、实现内存拷贝,功能类似于memcpy,可以不实现内存重叠拷贝,不能使用任何库函数
dest比src低,则可以从s头开始拷贝; dest比src高,则为了保证s的数据不会被覆盖,所以要从s的末尾开始拷贝
#include<stdio.h>
#include<assert.h>
void* my_memcpy(void* dest,const void* src, size_t size)
{
assert(dest);
assert(src);
if (dest <= src)
{
char* d = (char*)dest;
char* s = (char*)src;
while (size--)
{
*d++ = *s++;
}
}
else
{
char* d = (char*)dest + size;
char* s = (char*)src + size;
while (size--)
{
*d-- = *s--;
}
}
return dest;
}
int main()
{
char str[] = "hello world";
char ptr[20];
my_memcpy(ptr, str, 10);
return 0;
}
实现内存的移动,功能类似于memmove,实现内存重叠拷贝,不能使用任何库函数
#include<stdio.h>
#include<assert.h>
void* my_memmove(void* dest, const void* src, size_t size)
{
assert(dest);
assert(src);
if ((char*)dest <= (char*)src || (char*)dest >= ((char*)src + size))//不交叉
{
char* d = (char*)dest;
char* s = (char*)src;
while (size--)
{
*d++ = *s++;
}
}
else//交叉
{
char* d = (char*)dest + size -1;
char* s = (char*)src + size -1;
while (size--)
{
*d-- = *s--;
}
}
return dest;
}
int main()
{
char str[] = "hello world";
char ptr[20];
my_memmove(ptr, str, 10);
return 0;
}
45、实现内存的设置,功能类似于memset,以字节设置内存的值
#include<stdio.h>
#include<assert.h>
void* my_memset(void* str,char c, size_t size)
{
assert(str);
char* s = (char*)str;
while (size--)
{
*s++ = c;
}
return str;
}
int main()
{
char s[] = "hello world";
printf("%s\n", s);
my_memset(s,'0', 11);
printf("%s\n", s);
return 0;
}