strcpy, strcmp, strlen, memcpy 实现
[cpp]#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char *StrCpy(char *dest, const char *src)
{
assert((dest != NULL) && (src != NULL));
char *str = dest;
while ((*dest ++ = *src ++) != '\0');
return str;
}
int Strlen(const char *str)
{
assert((str != NULL));
int len = 0;
while (*str ++)
{
len++;
}
return len;
}
int StrCmp(const char *str1, const char *str2)
{
assert((str1 != NULL) && (str2 != NULL));
int rt = 0;
while ( !(rt = *(unsigned char *)str1 - *(unsigned char*)str2 ) && *str2)
{
str1 ++;
str2 ++;
}
if (rt > 0)
{
rt = 1;
}
else if (rt < 0)
{
rt = -1;
}
return rt;
}
//为了解决内存重叠的现象
void *MemCpy(void *dst, const void *src, size_t count)
{
char *pdst = static_cast<char *>(dst);
const char *psrc = static_cast<const char *>(src);
if (pdst > psrc && pdst < psrc + count)
{
for (int i = count - 1; i >= 0; i--)
{
pdst[i] = psrc[i];
}
}
else
{
for (int i = 0; i < count; i++)
{
pdst[i] = psrc[i];
}
}
return dst;
}
// memcpy 实现源码
void * __cdecl memcpy (
void * dst,
const void * src,
size_t count
)
{
void * ret = dst;
while (count--) {
*(char *)dst = *(char *)src;
dst = (char *)dst + 1;
src = (char *)src + 1;
}
return(ret);
}
int main()
{
char str2[100] = "abcd";
char *str1 = (char *)malloc(100);
str1= str2 + 2;
//考虑了内存重叠
MemCpy(str1, str2, 5);
printf("调用MemCpy后str1的内容: %s\n", str1);
//未考虑内存重叠
memcpy(str1, str2, 5);
printf("调用memcpy后str1的内容: %s\n", str1);
while(1);
}
补充:软件开发 , C++ ,