通过代码实现mem系列的函数
memcpy memmove memcmp memset
1.memcpy
把一块内存中的数据拷贝到另一个内存中
void* myMemcpy(void* dest, const void* src, size_t num) {
assert(dest != NULL);
assert(src != NULL);
assert(num != 0);
//按照字节为单位进行拷贝
char* cdest = (char*)dest;
const char* csrc = (const char*)src;
for (size_t i = 0; i < num; i++) {
cdest[i] = csrc[i];
}
return dest;
}
2.memmove
可以处理memcpy中处理不了的内存重叠问题(倒着拷贝)
void* myMemmove(void* dest, const void* src, size_t num) {
assert(dest != NULL);
assert(src != NULL);
assert(num != 0);
//按照字节为单位进行拷贝
char* cdest = (char*)dest;
const char* csrc = (const char*)src;
if (csrc <= cdest && cdest <= csrc + num) {
//如果内存重叠了,倒着拷贝
for (size_t i = num; i > num; i--) {
cdest[i-1] = csrc[i-1];
}
return dest;
}
else {
//如果不重叠 正着拷贝
for (size_t i = 0; i < num; i++) {
cdest[i] = csrc[i];
}
return dest;
}
}
3.memcmp
比较两个内存中内容的大小关系
与strncmp区别:不用考虑\0
int myMemcmp(const void* ptr1, const void* ptr2, size_t num) {
assert(ptr1 != NULL);
assert(ptr2 != NULL);
assert(num != 0);
const char* cptr1 = (const char*)ptr1;
const char* cptr2 = (const char*)ptr2;
for (size_t i = 0; i < num; i++) {
if (cptr1[i] < cptr2[i]) {
return -1;
}
else if (cptr1[i] > cptr2[i]) {
return 1;
}
else {
continue;
}
}
return 0;
}
4.memset
将ptr中当前位置中的后num个字节用value替换,并返回ptr
void* myMemset(void* ptr, int value, size_t num) {
assert(ptr != NULL);
assert(num != 0);
char* cptr = (char*)ptr;
for (size_t i = 0; i < num; i++) {
cptr[i] = (char)value;
}
return ptr;
}