内存拷贝函数
//实现拷贝不重叠的内存块
void* memcpy1(void* dst,const void* src,size_t count)
{
char* pTo = (char*)dst;
char* pFrom = (char*)src;
assert(dst != NULL && src != NULL);
assert(pTo >= pFrom+count || pTo <= pFrom-count);//防止内存重叠(over lap)
while(count-- > )
{
*pTo++ = *pFrom++;
}
return dst;
}
#include<stdio.h> char* mystrcat(char* str1,char* str2)//连接
{
char* p=str1;
while (*str1 !='\0')
{
str1++;
}
// while(*str1++);
while (*str2 != '\0')
{
*str1=*str2;
str1++;
str2++;
}
// while (*str1++ = *str2++);
*str1='\0';
return p;
} char* mystrcpy(char* str1,char* str2)
{
char*p = str1;
while (*str1++ = *str2++);
return p;
} char* mystrncpy(char* str1,char* str2,int n)
{
char* p=str1;
for (;*str2!='\0'&&n>;n--)
{
*str1 = *str2;
str1++;
str2++;
}
*str1='\0';
return p;
} int mystrcmp(char* str1,char* str2)
{
while()
{
if(*str1==*str2 && *str1 !='\0')
{
str1++;
str2++;
}
else if (*str1==*str2 && *str1=='\0')
return ;
else if(*str1>*str2)
return ;
else
return -;
}
}
字符串拷贝
#include <iostream>
#include <string.h> using namespace std; char* Mystrcpy(char* dst,const char* src)
{
if(dst == NULL || src == NULL)
return NULL;
int i = ;
for(i = ;src[i] != '\0';i++)
{
dst[i] = src[i];
}
dst[i] = '\0';
return dst;
}
char* Mystrncpy(char *dest, const char *src, size_t n)
{
if(dest == NULL || src == NULL)
return NULL;
int i;
for (i = ; i < n && src[i] != '\0'; i++)
dest[i] = src[i];
for ( ; i < n; i++)
dest[i] = '\0'; return dest;
} int main()
{
char dst[];
char dst1[];
char src[] = "hello";
Mystrcpy(dst,src);
cout << dst << endl;
Mystrncpy(dst1,src,);
cout << dst1 << endl;
return ;
}
//结果:
/*
hello
hel
*/