strcpy
代码
char* mystrcpy(char* dst, const char* src) {
if((dst == nullptr)||(src == nullptr)) return nullptr;
char* ret = dst;
while ((*dst++ = *src++) != '\0');
return ret;
}
char* mystrcpy(char* dst, const char* src) {
if (dst == nullptr || src == nullptr) return nullptr;
return (char*)mymemcpy(dst, src, mystrlen(src)+1);
}
注意问题
- const修饰源字符串
- 空指针检查
- ret保存原始的dst指针,即字符串开头
- 返回char*,为了支持链式表达式如
int l=strlen(strcpy(strA,strB));
- dst和src所指的内存区域不可以重叠
- dst需要分配内存
memcpy
代码
#include <iostream>
using namespace std;
void* mymemcpy(void* dest, const void* src, size_t n) {
if (dest == nullptr || src == nullptr || n == 0) return nullptr;
void* ret = dest;
if (dest < src || (char*)src + n < dest) {
size_t count = n / sizeof(size_t);
while (count--) {
*(size_t*)dest = *(size_t*)src;
dest = (size_t*)dest + 1;
src = (size_t*)src + 1;
}
count = n % sizeof(size_t);
while (count--) {
*(char*)dest = *(char*)src;
dest = (char*)dest + 1;
src = (char*)src + 1;
}
}
else {
dest = (char*)dest + n - 1;
src = (char*)src + n - 1;
while (n--) {
*(char*)dest = *(char*)src;
dest = (char*)dest - 1;
src = (char*)src - 1;
}
}
return ret;
}
int main() {
char dest[] = "12345678901234567890";
char src[] = "123456789123456789";
my_memcpy(dest, src, strlen(src) + 1);
cout << dest << endl;
return 0;
}
strcat
代码
char* mystrcat(char* dst, const char* src) {
if (dst == nullptr || src == nullptr) return nullptr;
char* pdst = dst;
while (*pdst != '\0') ++pdst;
while (*pdst++ = *src++);
return dst;
}
注意问题
- dst要有容纳src的长度
- dst和src所指的内存区域不可以重叠
strlen
代码
size_t mystrlen(const char* ptr) {
if (ptr == nullptr) return 0;
size_t ret = 0;
while (*ptr++ != '\0') ++ret;
return ret;
}
memset
代码
void* mymemset(void* ptr, int ch, size_t n) {
if (ptr == nullptr || n <= 0) return nullptr;
char* pptr = (char*)ptr;
while (n--) *pptr++ = ch;
return ptr;
}